gpt4 book ai didi

javascript - 如何使用 winston logger 记录 Node 错误?

转载 作者:搜寻专家 更新时间:2023-10-31 22:44:29 28 4
gpt4 key购买 nike

在我的 Node 应用程序中,我使用 Winstonjs记录器。今天我的应用程序似乎以某种方式卡住,但它无法记录某些内容。我停止了应用程序并手动运行它,结果显示了这个错误

ReferenceError: totalValue is not defined

我的代码显然有错误,但我的主要问题是我无法从 Winston 日志中获知。

我在下面粘贴了我的 Winston 实现。我创建它是为了可以简单地使用 log('The log message');。但这不会记录任何发生的 Node 错误。

有谁知道如何将每个发生的 Node 错误记录到我的 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 - 如何使用 winston logger 记录 Node 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49679240/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com