简体   繁体   English

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

[英]Error logging with express.logger in node.js

I am attempting to log only certain events to a file via express.logger(...) with a custom function and it is hanging when the response and request do not meet the criteria I have set. 我试图通过带有自定义功能的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...
   }
  });
 )

return '' in the else does not work. 在else中返回''不起作用。 It hangs, my guess is that its not allowing the response to finish/send. 它挂起了,我猜是它不允许响应完成/发送。

Perhaps I should use a different method to log, but I like the simplicity of the express middleware since it allows me to not have to include log messages everywhere - or can I get around that as well and have a listener for the certain events.. 也许我应该使用其他方法进行日志记录,但是我喜欢快速中间件的简单性,因为它使我不必到处都包含日志消息-或者我也可以解决这个问题并为某些事件提供侦听器。

Any ideas on what I should have in the else? 关于其他方面我应该有什么想法? Or suggestions on a better method? 还是有关更好方法的建议?

You need to understand that the middleware API is based on asynchronous callbacks, not synchronous return values. 您需要了解中间件API是基于异步回调而不是同步返回值的。 The return value of your middleware function will be entirely ignored. 您的中间件函数的返回值将被完全忽略。 You need to follow this mold: 您需要遵循以下步骤:

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