2014-11-17 21 views
0

我只想記錄會使系統崩潰到error.log單獨文件的錯誤。ExpressJS fremework(nodejs)僅將堆棧錯誤記錄到文件

林已經在使用這個代碼與摩根登錄http請求到一個文件:

// create a write stream (in append mode) 
var accessLogStream = fs.createWriteStream(__dirname + '/logs/access.log', {flags: 'a'}) 
// setup the logger 
app.use(logger('short', {stream: accessLogStream})); 

但我想登錄到一個單獨的文件(error.log中)這種應用程序的錯誤:

//Error handling, avoiding crash 
process.on('uncaughtException', function (err) { 
    console.error(err); 
    console.log("Node NOT Exiting..."); 
}); 

如何將error.stack記錄到該文件?

在此先感謝。

+0

注:http://expressjs.com/guide/error-handling.html –

回答

1
process.on('uncaughtException', function (err) { 
    console.error(err); 
    console.log("Node NOT Exiting..."); 
    accessLogStream.write(err.stack); 
}); 

只要寫入這樣的流應該工作!我雖然沒有測試過,但可能會因使用異步編寫而導致一些問題。我通常只是推送一個對象到數據庫。喜歡的東西

{ 
    err : myError, 
    time : new Date() 
} 
0

基於的Audun答案:

//Create error log Stream 
var errorLogStream = fs.createWriteStream(__dirname + '/logs/error.log', {flags: 'a'}) 

//Error handling, avoiding crash 
process.on('uncaughtException', function (err) { 

var date = new Date(); 
    console.error(err); 
    errorLogStream.write(date+ '\n'+ err.stack+'\n\n'); 

}); 

日誌輸出:

Mon Nov 17 2014 02:21:05 GMT-0300 (ART) 
TypeError: Cannot read property 'payment_credits' of null 
    at Promise.<anonymous> (/home/routes/api/chainWebhook.js:65:26) 
    at Promise.<anonymou>(/home//node_modules/mongoose/node_modules/mpromise/lib/promise.js:177:8) 
    at Promise.emit (events.js:95:17)