首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >电子中的console.log钩子

电子中的console.log钩子
EN

Stack Overflow用户
提问于 2017-12-30 16:43:43
回答 2查看 2.7K关注 0票数 0

我想联系电子行业的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调用。

EN

回答 2

Stack Overflow用户

发布于 2017-12-30 17:38:50

我认为这可以像这样通过覆盖console.logconsole.error来完成:

代码语言:javascript
运行
复制
var log = require("electron-log");

console.log = function (message) {
  log.info(message);
}
console.error = function (message) {
  log.error(message);
}

或者,如果您希望保留旧函数和/或将所有消息存储在一个数组中以供以后使用,则可以使用以下函数:

代码语言:javascript
运行
复制
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应该与一些适配一起工作:

代码语言:javascript
运行
复制
// 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将所有消息记录到它的开发人员控制台。

票数 3
EN

Stack Overflow用户

发布于 2022-03-02 03:00:20

您可以挂钩到WebContent对象的console-message事件(可从BrowserViewBrowserWindow上的webContent属性获得)。

请注意,它只将其作为字符串提供,因此如果您登录一个对象,它将被接收为[object Object]

有关更多信息,请参阅the docs

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48032326

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档