在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();
});
我对更优雅的解决方案感兴趣,例如使用finish
事件,但我无法在此上下文中访问响应消息。
app.use(function(req, res, next) {
res.on('finish', function() {
// console.log(?);
});
next();
});
答案 0 :(得分:1)
我使用了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)
答案 1 :(得分:0)
答案 2 :(得分:0)
与摩根'和'旋转文件流',您可以记录交易(请求和响应)并将其存储在一个区间内。
var express= require('express');
var router = express.Router();
//we get an instance of express
var app = express();
var rfs = require('rotating-file-stream');
var morgan = require('morgan');
//log file rotation
var logDirectory = path.join(__dirname, 'log')
// ensure log directory exists
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)
// create a rotating write stream
var accessLogStream = rfs('access.log', {
interval: '1d', // rotate daily
path: logDirectory
});
app.use(morgan('combined', {stream: accessLogStream}));