记录 Express 中的所有 HTTP 响应

Dio*_*oso 0 http node.js express

在 Express 中记录所有 HTTP 响应的最佳方法是什么?

我能够让它工作的唯一方法是猴子修补end事件。

app.use(function(req, res, next) {
  var rEnd = res.end;

  res.end = function(chunk, encoding, callback) {
    console.log(chunk.toString('utf8');
    rEnd.apply(this, arguments);
  };

  next();
});
Run Code Online (Sandbox Code Playgroud)

我对更优雅的解决方案感兴趣,例如使用finish事件,但我无法访问此上下文中的响应消息。

app.use(function(req, res, next) {

  res.on('finish', function() {
    // console.log(?);
  });

  next();
});
Run Code Online (Sandbox Code Playgroud)

Dio*_*oso 6

我使用了express-winston,它为请求和错误记录提供了一个中间件。

import express from 'express'
import winston from 'winston'
import expressWinston from 'express-winston'
import routes from './routes'

const app = express()

// Log the whole request and response body
expressWinston.requestWhitelist.push('body')
expressWinston.responseWhitelist.push('body')

// Logger makes sense before the router
app.use(expressWinston.logger({
  transports: [
    new winston.transports.Console({
      json: true,
      colorize: true
    })
  ]
}))

// Now we can tell the app to use our routing code
app.use(routes);

// Error logger makes sense after the router
app.use(expressWinston.errorLogger({
  transports: [
    new winston.transports.Console({
      json: true,
      colorize: true
    })
  ]
}))

app.listen(3000)
Run Code Online (Sandbox Code Playgroud)