Morgan Logger + Express.js: writing file AND showing in console

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!

Answers:

Answer

From github

var logger = require('morgan');

app.use(logger('common', {
    stream: fs.createWriteStream('./access.log', {flags: 'a'})
}));
app.use(logger('dev'));
Answer

Here you go brother ! Its almost using everything you provided. 100% working test result.

//Logger: production as well as dev. You can set morgan to log differently depending on your environment

 if(app.get("env")=="production") {

        var accessLogStream = fs.createWriteStream(__dirname + '/logs/' + "access.log", {flags: 'a'});
        app.use(morgan({stream: accessLogStream}));
    }
     else {
        app.use(morgan("dev")); //log to console on development
    }

N.B i have created logs folder and i have access.log file there :).

If you would like to test BOOT YOU NODEJS AS NODE_ENV=production.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.