【发布时间】:2018-10-03 10:04:57
【问题描述】:
我有一个用 Node 编写的程序,我在其中使用 Winstonjs 进行日志记录。我还有一个异常处理程序,以便节点异常/错误也到达我的日志。我现在有一个问题。当我使用node index.js(而不是pm2)从命令行运行脚本时,脚本会在出现错误时静默结束。
看看我下面的示例代码。我添加了三个console.log()s,它们试图记录一个未定义的变量。当我使用node index.js 运行脚本时,它给了我一个ReferenceError 来表示第一个错误的console.log(undefinedVariable),正如预期的那样。当我现在删除第一个和/或第二个 console.log 时,脚本会静默结束。
"use strict";
let winston = require('winston');
const path = require('path');
const PRODUCTION = false;
// LOGGING
const myFormat = winston.format.printf(info => {
return `${info.timestamp} ${info.level}: ${info.message}`;
});
console.log(undefinedVariable); // THIS GIVES A REFERENCE ERROR
const logger = winston.createLogger({
level: 'debug',
format: winston.format.combine(winston.format.timestamp(), myFormat),
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' })
]
});
console.log(undefinedVariable); // THIS DOES NOT GIVE A REFERENCE ERROR, BUT ENDS THE SCRIPT SILENTLY
if (!PRODUCTION) {
// If we're not in production then also log to the `console`
logger.add(new winston.transports.Console(
{format: winston.format.combine(winston.format.timestamp(), myFormat), level: 'debug'}
));
}
console.log(undefinedVariable); // THIS ALSO DOES NOT GIVE A REFERENCE ERROR, BUT ENDS THE SCRIPT SILENTLY
function log(message, level='debug'){
// Levels: error, warn, info, verbose, debug, silly
const e = new Error();
const regex = /\((.*):(\d+):(\d+)\)$/
const match = regex.exec(e.stack.split("\n")[2]);
let log_source = path.basename(match[1]) + ':' + match[2]; // eg: index.js:285
if (typeof message === 'object'){
message = JSON.stringify(message);
}
logger[level](log_source + ' - ' + message);
}
我正在运行 Winstonjs 版本 3.0.0-rc5。我知道这还不是最终的 3.0 版本,但我想我只是在这里犯了一个错误。
有人知道我在这里做错了什么吗?欢迎所有提示!
【问题讨论】:
标签: javascript node.js logging exception-handling winston