Morgan's documentation describes that it's possible to split the logging of requests and responses:
split / dual logging
The
morgan
middleware can be used as many times as needed, enabling combinations like:
- Log entry on request and one on response
- Log all requests to file, but errors to console
In their only related example, there are some comments describing that one middleware will log error responses to console, and another requests to file:
// log only 4xx and 5xx responses to console app.use(morgan('dev', { skip: function (req, res) { return res.statusCode < 400 } })) // log all requests to access.log app.use(morgan('common', { stream: fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'}) }))
Which seems to achieve the second example of logging all requests to file and errors to console, but not the first one.
I'm a bit lost, I couldn't understand what's telling morgan
to log only request or only responses. Do I have to concern where to place those middlewares properly?
Currently, I have a single log entry for both request and response, I guess:
morgan('[:date[clf]] :remote-addr :url :method HTTP/:http-version :status :remote-user :res[content-length] :referrer :user-agent :response-time ms', {
stream: {
write: (message) => {
winston.silly(message.trim());
}
}
});
So, how can I properly log requests in a morgan
middleware call, and responses in another?