我正在寻找 Hook 到 Electron 中的console.log。
我尝试按照此处提到的步骤操作:https://stackoverflow.com/a/9624028/2091948
虽然上述方法在 Node.js 中运行良好,但同样的方法在 Electron 中不起作用(而 Electron 又基于 Node.js)
如何在 Electron 中实现这一目标?
我需要捕获对 console.log 和 console.error 的所有调用,以便我可以使用模块 electron-log
( https://www.npmjs.com/package/electron-log ) Hook 所有 console.log 和 console.error来电。
最佳答案
我认为这可以通过覆盖 console.log
或 console.error
来完成,如下所示:
var log = require("electron-log");
console.log = function (message) {
log.info(message);
}
console.error = function (message) {
log.error(message);
}
或者,如果您想保留旧函数和/或将所有消息存储在数组中以供以后使用,您可以使用以下函数:
var log = require("electron-log"), msgInfo = [], msgErr = [];
// Preserve the old, built-in functions
console.log_old = console.log;
console.error_old = console.error;
console.log = function (message) {
msgInfo.push(message);
log.info(message);
}
console.error = function (message) {
msgErr.push(message);
log.error(message);
}
您可以在浏览器窗口中使用这些函数,对于主进程,code您已经提到应该进行一些调整:
// https://stackoverflow.com/a/9624028, written by "kevin"
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);
}),
// require electron-log
log = require("electron-log");
// goes to our custom write method
console.log('foo');
console.log('bar');
unhook_stdout();
console.log('Not hooked anymore.');
// Now do what you want with logs stored by the hook
logs.forEach(function(_log) {
// Either log the contents of the message array...
//console.log('logged: ' + _log);
// ...or use electron-log to actually log them.
log.info(_log);
});
这段代码将在主进程中工作,因为 NodeJS 会创建到 stdout
的流。在渲染器过程中,您必须使用我上面提到的函数,因为 Electron 不会创建任何流,而是让 Chromium 将所有消息记录到其开发者控制台。
关于javascript - Hook 到 Electron 中的 console.log,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48032326/