Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 376
Andrea Silvestri Avatar asked Dec 01 '14 14:12

Andrea Silvestri


2 Answers

From github

var logger = require('morgan');

app.use(logger('common', {
    stream: fs.createWriteStream('./access.log', {flags: 'a'})
}));
app.use(logger('dev'));
like image 58
jwags Avatar answered Sep 27 '22 21:09

jwags


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.

like image 32
Daniel Adenew Avatar answered Sep 27 '22 19:09

Daniel Adenew