如何在node.js过程错误事件上logging堆栈跟踪
我的节点进程正在死亡,当进程退出时,我似乎无法login到文件。 这是一个由node.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);
还尝试创build事件处理程序的error
, uncaughtException
。 手动杀死我的进程( kill {pid}
)什么都kill {pid}
。 文件process.log
被创build,但没有任何内容。 可写stream是否需要在完成时调用stream.end()
?
根据Node.js文档:
当Node.js进程即将退出时,会发出'exit'事件:
- 显式调用
process.exit()
方法。- Node.js事件循环不再有任何额外的工作要执行。
所以,如果你开始一个永远不会结束的进程,它永远不会触发。
而且,可写stream不需要closures:
如果
autoClose
(来自createWriteStream
的选项)设置为true
(默认行为)出错或结束,文件描述符将自动closures。
但是,默认情况下, createWriteStream
函数会打开标记为'w'
的文件,这意味着文件每次都会被覆盖(也许这就是为什么你总是看到它是空的)。 我build议使用
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', '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`); });
我build议你把代码放在一个try catch块中,以找出它的代码或是一些导致程序终止的外部原因。 然后检查事件后的日志…
try { //your code }catch(e) { console.log(e.stack); }