简体   繁体   中英

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.

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. 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. 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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