Reputation: 22277
What's the best approach to log all HTTP responses in Express?
The only way I was able to got it working was monkey patching the end
event.
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();
});
I'm interested in a more elegant solution, for example using the finish
event, but I'm unable to access the response message on this context.
app.use(function(req, res, next) {
res.on('finish', function() {
// console.log(?);
});
next();
});
Upvotes: 0
Views: 8781
Reputation: 63
With 'Morgan' and 'Rotating File Stream', you can both log the transactions(request and response) and store it in an interval.
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}));
Upvotes: 1
Reputation: 22277
I've used express-winston which provides a middleware for request and error logging.
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)
Upvotes: 7