【问题标题】:How to log stack trace on node.js process error event如何在 node.js 进程错误事件上记录堆栈跟踪
【发布时间】:2017-09-20 19:10:58
【问题描述】:

我的节点进程正在死去,当进程退出时,我似乎无法登录到文件。这是一个长时间运行的进程,直接用node index.js 调用:

// index.js
const fs = require('fs');

exports.getAllCars = (process => {
    if (require.main === module) {
        console.log(`Running process: ${process.getgid()}.`);
        let out = fs.createWriteStream(`${__dirname}/process.log`);

        // trying to handle process events here:
        process.on('exit', code => out.write(`Exit: ${code}`));

        return require('./lib/cars').getAllCars();
    } else {
        return require('./lib/cars').getAllCars;
    }
})(process);

还尝试为erroruncaughtException 创建事件处理程序。手动终止我的进程时没有任何效果(使用kill {pid})。文件process.log 已创建,但没有任何内容。可写流是否需要在完成时调用stream.end()

【问题讨论】:

  • kill $PID 发送一个 SIGTERM,因此请尝试为这些添加一个 signal handler
  • 嗯,我只是在使用kill {pid} 进行测试。我真正的用例是当进程刚刚结束而没有在任何地方记录任何错误时。自从我将错误处理放在那里以来,我还没有发生过这种情况。通常该过程会在约 4 小时后意外终止。
  • 如果它在没有记录任何错误的情况下死掉,我的猜测是进程被杀死的外部原因(例如,Linux 上的 OOM 杀手)。
  • 当然,现在我已经为exiterroruncaughtException 设置了处理程序,该过程运行良好...¯\_(ツ)_/¯

标签: node.js error-handling


【解决方案1】:

根据 Node.js 文档:

'exit' 事件在 Node.js 进程即将退出时触发 由于以下任一原因:

  • process.exit() 方法被显式调用。
  • Node.js 事件循环不再需要执行任何额外的工作。

因此,如果您启动一个不应该结束的进程,它就永远不会触发。

此外,可写流不需要关闭:

如果autoClose(来自createWriteStream 的选项)设置为true(默认 行为)发生错误或结束文件描述符将被关闭 自动。

然而,createWriteStream 函数默认打开带有标志'w' 的文件,这意味着文件每次都会被覆盖(可能这就是你总是看到它为空的原因)。我建议使用

fs.appendFileSync(file, data)

这里是想要监听的事件:

//catches ctrl+c event
//NOTE:
//If SIGINT has a listener installed, its default behavior will be removed (Node.js will no longer exit).
process.on('SIGINT', () => {
    fs.appendFileSync(`${__dirname}/process.log`, `Received SIGINT\n`);
    process.exit()
});

//emitted when an uncaught JavaScript exception bubbles
process.on('uncaughtException', (err) => {
    fs.appendFileSync(`${__dirname}/process.log`, `Caught exception: ${err}\n`);
});

//emitted whenever a Promise is rejected and no error handler is attached to it
process.on('unhandledRejection', (reason, p) => {
    fs.appendFileSync(`${__dirname}/process.log`, `Unhandled Rejection at: ${p}, reason: ${reason}\n`);
});

【讨论】:

    【解决方案2】:

    我建议您将代码放在 try catch 块中,以找出是代码还是导致程序终止的外部原因。 然后在事件发生后查看日志...

    try {
      //your code 
    }catch(e) {
      console.log(e.stack);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-22
      • 2022-11-13
      • 1970-01-01
      • 2017-07-20
      • 2010-12-29
      • 2014-08-12
      • 2014-11-01
      • 1970-01-01
      • 2018-09-19
      相关资源
      最近更新 更多