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

前端 未结 2 1364
面向向阳花
面向向阳花 2021-02-05 11:26

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\'         


        
相关标签:
2条回答
  • 2021-02-05 12:18

    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.

    0 讨论(0)
  • 2021-02-05 12:24

    From github

    var logger = require('morgan');
    
    app.use(logger('common', {
        stream: fs.createWriteStream('./access.log', {flags: 'a'})
    }));
    app.use(logger('dev'));
    
    0 讨论(0)
提交回复
热议问题