Node.js - 日志记录/使用摩根和温斯顿 [英] Node.js - logging / Use morgan and winston

查看:37
本文介绍了Node.js - 日志记录/使用摩根和温斯顿的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用 morgan 来记录我们的快速转换:

we use morgan in order to log our express transformation:

var morgan  = require('morgan');
morgan('combined');
// a format string
morgan(':remote-addr :method :url :uuid');
// a custom function
morgan(function (req, res) {
  return req.method + ' ' + req.url + ' ' + req.uuid;
})

此外,我们使用 winston 来记录我们的其他日志:

Also, we use winston in order to log our other logging:

var winston = require('winston');
var logger = new (winston.Logger)({
  transports: [
         new (winston.transports.Console)({ level: 'info' }),
          new (winston.transports.File)({ filename: '/var/log/log-file.log' })
  ]
});

有没有办法将两个记录器结合在一起?现在的情况是 morgan 写入我的标准输出,当 winston 写入 /var/log/log-file.log 时.

Is there any way to combine the two loggers together? the situation now is that morgan is write to my standard output, when winston writes to /var/log/log-file.log.

我希望记录器文件能够结合快速转换信息和我想要的其他信息 (logger.info())..

I wish that the logger file will combine from the express transformation information, and from the other information I want (logger.info())..

推荐答案

这篇文章非常适合您想做的事情.

This article does an excellent job for what you want to do.

http://tostring.it/2014/06/23/advanced-logging-with-nodejs/

对于您的特定代码,您可能需要这样的东西:

For your specific code you probably need something like this:

var logger = new winston.Logger({
    transports: [
        new winston.transports.File({
            level: 'info',
            filename: './logs/all-logs.log',
            handleExceptions: true,
            json: true,
            maxsize: 5242880, //5MB
            maxFiles: 5,
            colorize: false
        }),
        new winston.transports.Console({
            level: 'debug',
            handleExceptions: true,
            json: false,
            colorize: true
        })
    ],
    exitOnError: false
});

logger.stream = {
    write: function(message, encoding){
        logger.info(message);
    }
};

app.use(require("morgan")("combined", { "stream": logger.stream }));

这将设置 Winston 将日志和文件写入控制台.然后就可以使用最后一个表达式将摩根中间件的输出传递给 winston.

This will set up Winston to write a log to the console as well as a file. Then you can use the last expression to pass output from the morgan middleware into winston.

这篇关于Node.js - 日志记录/使用摩根和温斯顿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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