Morgan Logger + Express.js: writing file AND showing in console
14,676
From github
var logger = require('morgan');
app.use(logger('common', {
stream: fs.createWriteStream('./access.log', {flags: 'a'})
}));
app.use(logger('dev'));
Author by
Andrea Silvestri
Updated on June 03, 2022Comments
-
Andrea Silvestri almost 2 years
I'm trying to use Morgan with Express.js to write a log file while showing my logs on the console as well. I'm using this code:
var logger = require('morgan'); var accessLogStream = fs.createWriteStream('./access.log', {flags: 'a'}); app.use(logger("dev",{stream: accessLogStream}));
But in this way I only get console logs and my access.log file remains empty.
If I do this instead (not specifying "dev"):
var logger = require('morgan'); var accessLogStream = fs.createWriteStream('./access.log', {flags: 'a'}); app.use(logger({stream: accessLogStream}));
I get the logs on my file but not on the console.
How can I obtain both the log on the console AND on the file?
Thank you in advance!
EDIT: at this moment I've found this solution:
app.use(logger({format:"[:date[clf]] :method :url :status :response-time ms",stream: { write: function(str) { accessLogStream.write(str); console.log(str); } }}));
But if you have a better one... you're welcome!