2012-06-28 35 views
1

我嘗試使用自定義函數僅通過express.logger(...)將某些事件記錄到文件中,並且當響應和請求不符合我設定的標準。在node.js中使用express.logger記錄錯誤

var express = require('express'), 
app = express.createServer(
    express.logger(function(req, res) { 
    var status = res.statusCode, 
    color = 32; 

    if (status >= 500) color = 31; 
    else if (status >= 400) color = 33; 
    else if (status >= 300) color = 36; 

    if (req.method==='POST' && req.originalUrl!=='/plankton') { 
    return '\033[90m' + req.method 
    + ' ' + req.originalUrl + ' ' 
    + '\033[' + color + 'm' + res.statusCode 
    + ' \033[90m' 
    + (new Date - req._startTime) 
    + 'ms\033[0m'; 
    } 
    else if (res.statusCode>=400) { 
    return '\033[90m' + req.method 
    + ' ' + req.originalUrl + ' ' 
    + ' ' + req.body + ' ' 
    + '\033[' + color + 'm' + res.statusCode 
    + ' \033[90m' 
    + (new Date - req._startTime) 
    + 'ms\033[0m'; 
    } else { 
// what should be inserted here? 
// I only want to log the above events... 
    } 
    }); 
) 

返回''在其他不起作用。它掛起,我的猜測是它不允許響應完成/發送。

也許我應該使用不同的方法來記錄日誌,但我喜歡簡單的快速中間件,因爲它可以讓我不必在任何地方都包含日誌消息 - 或者我也可以解決這個問題,並且有一個監聽器某些事件..

關於我應該在其他方面有什麼想法?或建議更好的方法?

回答

1

您需要了解中間件API基於異步回調,而不是同步返回值。中間件功能的返回值將被完全忽略。您需要遵循此模具:

function (req, res, next) { 
    //look at req 
    //do whatever logging you decide you want to do 
    //Tell express that you are done and it can move along the middleware chain 
    next(); 
} 
+0

謝謝。我對異步世界非常陌生。 – Jacob