我想在电子中挂钩console.log
我尝试按照此处提到的步骤进行操作:https://stackoverflow.com/a/9624028/2091948
虽然上述方法在node.js中运行良好,但这种方法在电子中不起作用(反过来又以node.js为基础)
我怎样才能在电子中实现这一目标?
我需要捕获对console.log和console.error的所有调用,以便我可以使用模块electron-log
(https://www.npmjs.com/package/electron-log)挂钩所有console.log和console.error调用。 / p>
答案 0 :(得分:2)
我认为这可以通过覆盖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将所有消息记录到它的开发者控制台。