Node.js错误日志包含更多信息

node.js error log include more information

本文关键字:信息 包含更 日志 js 错误 Node      更新时间:2023-09-26

我像这样启动我的node.js服务器:

sudo NODE_ENV=production forever start -o out.log -e error .log server.js

我偶尔会在错误日志中出现错误。

但是我得到的是这样的东西:

Cannot read property 'length' of undefined
    at eval at <anonymous> (/home/ubuntu/www/node_modules/jade/lib/jade.js:161:8)
    at anonymous (eval at <anonymous> (/home/ubuntu/www/node_modules/jade/lib/jade.js:161:8))
    at Object.<anonymous> (/home/ubuntu/www/node_modules/jade/lib/jade.js:166:12)
    at ServerResponse._render (/home/ubuntu/www/node_modules/express/lib/view.js:422:21)
    at ServerResponse.render (/home/ubuntu/www/node_modules/express/lib/view.js:315:17)
    at callbacks (/home/ubuntu/www/node_modules/express/lib/router/index.js:272:11)
    at Promise.<anonymous> (/home/ubuntu/www/helper/auth.js:118:11)
    at Promise.<anonymous> (/home/ubuntu/www/node_modules/mongoose/lib/promise.js:120:8)

如何使错误日志显示更多信息,例如错误发生的日期和时间?

像这样使用'uncaughtException'事件:

process.on('uncaughtException', function (err) {
  console.log('Caught exception: ' + err);
});
setTimeout(function () {
  console.log('This will still run.');
}, 500);
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');

你可以记录一个日期和任何你想在回调中注销的东西。

更多的进程在这里:http://nodejs.org/docs/v0.4.12/api/process.html event_uncaughtException_

如果需要日期时间信息,可以使用require('util').log()

打印

如果你还想阻止你的应用程序退出,你可以捕获未捕获的异常

var util = require('util');
process.on('uncaughtException', function (err) {
//Traceout the error details    
console.error(err.stack)
  util.log('Caught exception: ' + err.message);
});

请记住,如果抛出异常,可能正在运行的回调序列将停止,因此如果继续运行应用程序,应用程序可能会出现奇怪的行为。在上面未捕获的异常处理程序中添加process.exit()可能是明智的。