编程语言
首页 > 编程语言> > javascript – 如何使用winston logger记录节点错误?

javascript – 如何使用winston logger记录节点错误?

作者:互联网

在我的节点应用程序中,我使用Winstonjs记录器.今天我的应用程序似乎冻结了,但它没有记录某些东西.我停止了应用程序并手动运行它,这显示了我的错误

ReferenceError: totalValue is not defined

我在代码中明显犯了一个错误,但我的主要问题是我从Winston日志中无法知道.

我在下面粘贴了我的Winston实现.我创建了这个,以便我可以简单地使用log(‘日志消息’);.但是这不记录任何发生的节点错误.

有谁知道如何将每个发生的节点错误都记录到我的Winston日志中?

const myFormat = winston.format.printf(info => {
    return `${info.timestamp} ${info.level}: ${info.message}`;
});
const logger = winston.createLogger({
    level: 'info',
    format: winston.format.combine(winston.format.timestamp(), myFormat),  // winston.format.json(),
    transports: [
        new winston.transports.File({filename: 'logs/error.log', level: 'error'}),
        new winston.transports.File({filename: 'logs/combined.log'}),
    ]
});
function log(message, level='info'){
    if (typeof message === 'object'){
        message = JSON.stringify(message);
    }
    logger[level](message);
}

解决方法:

Winston可以为您记录例外情况.来自文档:Exceptions

With winston, it is possible to catch and log uncaughtException events from your process. With your own logger instance you can enable this behavior when it’s created or later on in your applications lifecycle:

const { createLogger, transports } = require('winston');

// Enable exception handling when you create your logger.
const logger = createLogger({
  transports: [
    new transports.File({ filename: 'combined.log' }) 
  ],
  exceptionHandlers: [
    new transports.File({ filename: 'exceptions.log' })
  ]
});

// Or enable it later on by adding a transport or using `.exceptions.handle`
const logger = createLogger({
  transports: [
    new transports.File({ filename: 'combined.log' }) 
  ]
});

// Call exceptions.handle with a transport to handle exceptions
logger.exceptions.handle(
  new transports.File({ filename: 'exceptions.log' })

标签:javascript,node-js,error-handling,logging,winston
来源: https://codeday.me/bug/20190622/1262671.html