繁体   English   中英

在node.js中使用express.logger记录错误

[英]Error logging with express.logger in 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...
   }
  });
 )

在else中返回''不起作用。 它挂起了,我猜是它不允许响应完成/发送。

也许我应该使用其他方法进行日志记录,但是我喜欢快速中间件的简单性,因为它使我不必到处都包含日志消息-或者我也可以解决这个问题并为某些事件提供侦听器。

关于其他方面我应该有什么想法? 还是有关更好方法的建议?

您需要了解中间件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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM