在我的 NodeJS 项目中使用 Winston 记录器,我找不到配置记录器以以下格式输出日志的方法:
[ 'timestamp' ] : [ 'level' ] -> 'message' [ if error: 跟踪其他内容 ]
我当前的格式如下:
const logger = winston.createLogger({
transports: new transports.Console({
format: format.combine(
format.errors({ stack: true }),
format.timestamp({ format: "MMM-DD-YYYY HH:mm:ss" }),
format.align(),
format.printf(
({ level, message, timestamp, stack }) =>
`[${timestamp}] [${level}]: ${message} ${level == "error" ? stack : ""}`
)
),
}),
});
记录例如:logger.error("Some text on error");
结果:[Jan-20-2022 14:20:43] [error]:一些错误文本未定义
问题是什么?
最佳答案
获取堆栈跟踪仅适用于具有 Error.stack
的 Error
对象。属性:
logger.error(new Error("Some text on error"));
请参阅 logform.format.errors
的文档:
The
errors
format allows you to pass in an instance of a JavaScriptError
directly to the logger. It allows you to specify whether not to include the stack-trace.
这是一个完整的 TypeScript/JavaScript 示例:
#!/bin/env ts-node-esm
import winston from 'winston';
const log = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.errors({stack: true}),
winston.format.timestamp({format: "YYYY-MM-DD HH:mm:ss.SSS"}),
winston.format.printf(({timestamp, level, message, stack}) => {
const text = `${timestamp} ${level.toUpperCase()} ${message}`;
return stack ? text + '\n' + stack : text;
}),
),
transports: [
new winston.transports.Console(),
],
});
function fail() {
throw new Error("Some text on error")
}
try {
fail();
}
catch(e) {
console.log("console");
console.log("abc", e);
console.log();
console.log("winston");
log.error("abc", e);
console.log();
log.info("No error");
log.error("No error");
}
输出:
console
abc Error: Some text on error
at fail (file:///home/max/src/quant-research/tests/ts-test.ts:20:11)
at file:///home/max/src/quant-research/tests/ts-test.ts:24:5
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:533:24)
at async loadESM (node:internal/process/esm_loader:91:5)
at async handleMainPromise (node:internal/modules/run_main:65:12)
winston
2023-02-22 02:37:00.063 ERROR abc Some text on error
Error: Some text on error
at fail (file:///home/max/src/quant-research/tests/ts-test.ts:20:11)
at file:///home/max/src/quant-research/tests/ts-test.ts:24:5
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:533:24)
at async loadESM (node:internal/process/esm_loader:91:5)
at async handleMainPromise (node:internal/modules/run_main:65:12)
2023-02-22 02:37:00.063 INFO No error
2023-02-22 02:37:00.064 ERROR No error
关于node.js - NodeJS Winston 记录器不打印跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70786287/