首页 文章

Node.js - 记录/使用摩根和温斯顿

提问于
浏览
68

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

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 来记录我们的其他日志记录:

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' })
     ]
    });

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

我希望 Logger 文件将结合来自快速转换信息和我想要的其他信息( logger.info() ) .

3 回答

  • 109

    本文对您想要做的事情做得很好 .

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

    对于您的特定代码,您可能需要以下内容:

    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 .

  • 9

    在打字稿中:

    let logger = new (winston.Logger)({
        exitOnError: false,
        level: 'info',
        transports: [
            new (winston.transports.Console)(),
            new (winston.transports.File)({ filename: 'app.log'})
        ]
    })
    
    class MyStream {
        write(text: string) {
            logger.info(text)
        }
    }
    let myStream = new MyStream()
    app.use(morgan('tiny', { stream: myStream }));
    
  • 7

    更新最后一行以删除警告

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

相关问题