requestLogger.js 1.3 KB
var moment = require('moment');


exports = module.exports = function (logger,settings) {


  return function (req, res, next) {
      var requestEnd = res.end
        , requestedUrl = req.originalUrl
        , startTime = new Date();
      var level = 'error';
      if(settings&&settings.output&&settings.output.level){
        level=settings.output.level;
      }

      // Proxy the real end function
      res.end = function (chunk, encoding) {
 
          var data = {
              'date': moment(startTime).format(),
              'statusCode': res.statusCode,
              'method': req.method,
              'responseTime': (new Date() - startTime),
              'deviceId':req.headers['device-id']||'',
              'xRequestId':req.headers['x-request-id']||'',
              'url': requestedUrl,
              'ip': req.headers['client-ip'] || req.ip || req.connection.remoteAddress,
              'userAgent':  req.headers['user-agent'] 
          };

          // Do the work expected
          res.end = requestEnd;
          res.end(chunk, encoding); 
          
          if(res.statusCode>=400){//响应错误
            logger.error(data);
          }else if('debug'==level){
            logger.debug(data);
          }else{
            logger.info(data);
          } 
      };
 
      next();
  };
};