Morgan Logger + Express.js:编写文件并在控制台中显示 [英] Morgan Logger + Express.js: writing file AND showing in console

查看:157
本文介绍了Morgan Logger + Express.js:编写文件并在控制台中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Morgan与Express.js来编写一个日志文件,同时在控制台上显示我的日志。
我使用这个代码:

  var logger = require('morgan'); 
var accessLogStream = fs.createWriteStream('./ access.log',{flags:'a'});
app.use(logger(dev,{stream:accessLogStream}));

但是这样我只得到控制台日志,我的access.log文件保持为空。 >

如果我这样做(不指定dev):

  var logger = require('morgan'); 
var accessLogStream = fs.createWriteStream('./ access.log',{flags:'a'});
app.use(logger({stream:accessLogStream}));

我收到我的文件上的日志,但不在控制台上。



如何获取控制台上的日志和文件?



提前谢谢!



编辑:
此时我发现了这个解决方案:

 code> app.use(logger({format:[:date [clf]]:method:url:status:response-time ms,stream:{
write:function(str)
{
accessLogStream.write(str);
console.log(str);
}
}}));

但如果你有一个更好的一个...欢迎你!

解决方案

github

  var logger = require('morgan'); 

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


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!

解决方案

From github

var logger = require('morgan');

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

这篇关于Morgan Logger + Express.js:编写文件并在控制台中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆