添加一个钩子来全局地loggingnode.js / express中的所有节点HTTP响应

我使用node.js和expression来处理HTTP请求和响应。 通过使用http.ServerRequest事件,我可以添加一个挂钩并loggingHTTP请求。 似乎没有http.ServerResponse事件,我想知道如何使用服务器发送的一段代码logging所有HTTP响应?

我创造了一个包装,做出这样的事情,出于类似的需求。 检查快速请求logging器

程序的核心是这样的,它包含一些额外的代码,所以你可以拥有自己的键值映射数据,每个请求logging:

 // Save the real end that we will wrap var rEnd = res.end; // To track response time req._rlStartTime = new Date(); // Proxy the real end function res.end = function(chunk, encoding) { // Do the work expected res.end = rEnd; res.end(chunk, encoding); // And do the work we want now (logging!) // Save a few more variables that we can only get at the end req.kvLog.status = res.statusCode; req.kvLog.response_time = (new Date() - req._rlStartTime); // Send the log off to winston var level = req.kvLog._rlLevel; delete req.kvLog._rlLevel; logger.log(level, '', req.kvLog); }; 

上面的代码在express中作为中间件运行。 看一下代码,如果还有其他问题,请在这里或者github与我联系。

不再需要monkeypatch,只要从node.js 0.8.12开始在end()函数上发出结束事件。

实际上,它最初是以0.8.8 结尾 发布的 (检查这个 ),但是它破坏了可写的stream的双工 ,所以它被重命名为完成。

如果您只想logging(请求和/或回复),请查看express-winston 。 不像摩根 ,它甚至可以logging请求/响应主体。

coffeescript示例:

 expressWinston.requestWhitelist.push('body') expressWinston.responseWhitelist.push('body') app.use(expressWinston.logger({ transports: [ new winston.transports.Console({ json: true, colorize: true }) ], meta: true, // optional: control whether you want to log the meta data about the request (default to true) msg: "HTTP {{req.method}} {{req.url}}", // optional: customize the default logging message. Eg "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}" expressFormat: true, // Use the default Express/morgan request formatting, with the same colors. Enabling this will override any msg and colorStatus if true. Will only output colors on transports with colorize set to true colorStatus: true, // Color the status code, using the Express/morgan color palette (default green, 3XX cyan, 4XX yellow, 5XX red). Will not be recognized if expressFormat is true ignoreRoute: function (req, res) { return false; } // optional: allows to skip some log messages based on request and/or response })); 

如果您对所有响应使用快速的res.send(),并且您不介意将代码插入快速模块,则可以插入

… / node_modules /快递/ lib中/ response.js:

 43 res.send = function(body, headers, status){ 44 console.log("\n...your log text here..." + body); 45 // allow status as second arg 46 if ('number' == typeof headers) { 47 status = headers, 48 headers = null; 49 } 

我不认为你可以听一个非错误的事件 – “closures”似乎没有触发res.send();. 我想这是因为send()总是在你的代码中调用。