如何在 Winstonjs 记录器中记录未处理的超时错误?

How to log Unhandled TimeoutError in Winstonjs logger?

我有一个节点应用程序,我在其中使用 Winstonjs 作为记录器。在我的记录器中,我有一个特定的部分用于记录这样的异常:

const myFormat = winston.format.printf(info => {
    return `${info.timestamp} ${info.level}: ${info.message}`;
});
const logger = winston.createLogger({
    level: "debug",
    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'}),
    ],
    exceptionHandlers: [
        new winston.transports.File({ filename: 'logs/exceptions.log' }),
        new winston.transports.File({ filename: 'logs/combined.log' })
    ],
    exitOnError: false
});

因此,任何异常都应记录在 logs/combined.loglogs/exceptions.log 中。

当我 运行 我的程序时,我现在有时会在我的 STDOUT 中收到以下错误,它来自 Sequelizejs 我用来写入我的 MySQL 数据库。

Unhandled rejection TimeoutError: ResourceRequest timed out
    at ResourceRequest._fireTimeout (/root/mmjs/node_modules/generic-pool/lib/ResourceRequest.js:62:17)
    at Timeout.bound (/root/mmjs/node_modules/generic-pool/lib/ResourceRequest.js:8:15)
    at ontimeout (timers.js:424:11)
    at tryOnTimeout (timers.js:288:5)
    at listOnTimeout (timers.js:251:5)
    at Timer.processTimers (timers.js:211:10)

此错误仅出现在标准输出中(当 运行 手动运行我的程序时),它不会出现在 combined.logexceptions.log 中。可能是因为这是错误而不是异常。不过,我不确定如何正确记录。

(我想我可以 wrap my whole code in a try/catch,但我想还有更好的方法.. :-))

有人可以帮我记录这个错误和类似的未捕获错误吗?

进程指的是节点。尝试在 index.js 中添加 unhandledRejection 检查或使用 proper winston exception handling:

"use strict";

const winston = require('winston');

const myFormat = winston.format.printf(info => {
    return `${info.timestamp} ${info.level}: ${info.message}`;
});
const logger = winston.createLogger({
    level: "debug",
    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'}),
    ],
    exceptionHandlers: [
        new winston.transports.File({ filename: 'logs/exceptions.log' }),
        new winston.transports.File({ filename: 'logs/combined.log' })
    ],
    exitOnError: false,
    // handleExceptions: true // Otherwise, you should use this in options.
});

process.on('unhandledRejection', (reason, promise) => {
    logger.debug(reason);
});

process.on('uncaughtException', (err) => {
    logger.debug(err);
});

但是,请在与 index.js 文件相同的目录中查看 package.json 文件。查看节点池的依赖项部分并将其版本更改为 "node-pool": "^3.4.2" 因为您描述的问题很可能在 3.1.8 版本中得到修复。