5

我使用 Mongo 设置了一个 Express 服务器,以在使用 React 对 Electron 应用程序进行调试测试期间记录控制台日志。

我只是使用 ajax 来发送我通常使用 console.log 打印的内容。这适用于我想要记录的单个事件,但是如何将整个 chrome 样式的控制台导出为一个对象,以便任何可以到达控制台的内容(例如:webpack 消息、来自其他组件的消息等)都可以作为一个对象访问我可以在上面做一个 POST。

基本上是一种记录您在控制台中看到的所有内容的方法,无论是来自第三方包还是我自己明确记录的内容。是否有控制台转储某种我在铬/电子/反应文档中没有看到的所有方法?

例子:

//import some debugger method to POST to server collecting logs

export function debugpost(logobject) {



$.ajax({
    type: "POST",
    url: "http://" + "192.168.0.94" + ":3000/tasks",

    headers: {

    },
    data: {
        log: logobject
    },
    success: function(data) {


    }.bind(this),
    error: function(errMsg) {
        console.log(errMsg);
    }.bind(this)
});
}

//simple way of recording logs in other component.
var testlogmessage = "This isn't right"

debugpost(testlogmessage);

将单个事件记录到服务器很容易。如何转储整个控制台?

下面提到的更新是绑定到进程stdout和stderr。我尝试了推荐的包 capture-console 以及这个代码片段:

var logs = [],

hook_stream = function(_stream, fn) {
    // Reference default write method
    var old_write = _stream.write;
    // _stream now write with our shiny function
    _stream.write = fn;

    return function() {
        // reset to the default write method
        _stream.write = old_write;
    };
},

// hook up standard output
unhook_stdout = hook_stream(process.stdout, function(string, encoding, fd) {
    logs.push(string);
});

然而,当使用 with react 时,两者都给我写这个错误:

TypeError: Cannot read property 'write' of undefined
hook_stream

当我在电子 main.js 中使用它时,该特定方法似乎可以很好地记录电子节点端。但是我无法让它在我的反应组件中工作。

4

2 回答 2

6

这样做的一种方法是console.log用您的自定义实现覆盖,因此每当代码的任何部分调用时console.log,调用都会被您的自定义函数拦截,您可以在其中使用一些 API 调用将消息记录到远程服务器。

记录消息后,您可以调用原始console.log方法。

以下示例显示了方法的自定义实现console.log

var orgLog = console.log;

console.log = function(message) {
  alert("Intercepted -> " + message); //Call Remote API to log the object.
  //Invoke the original console.log
  return orgLog(message);
}

let a = {
  foo: "bar"
};
console.log(a);

于 2018-12-17T06:43:44.853 回答
3

您可以绑定到流程模块中的stdoutstderr流。

看看 npm capture-console。您将需要从任何渲染器进程以及主进程中捕获控制台输出。

更新

看来电子对渲染器进程标准输出流做了一些奇怪的事情。您最好使用自定义日志记录解决方案,例如电子日志并从书面日志文件同步日志。

于 2018-12-08T00:43:31.660 回答