node.js - NodeJS Winston 记录器不打印跟踪

标签 node.js logging winston

在我的 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.stackError 对象。属性:

logger.error(new Error("Some text on error"));

请参阅 logform.format.errors 的文档:

The errors format allows you to pass in an instance of a JavaScript Error 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/

相关文章:

mysql - 解析器在查询 MySQL 数据库时将函数作为错误抛出?

javascript - 类型错误 : boolean is not a function

javascript - NodeJS 变量作用域

java - spring boot .war tomcat 应用程序日志不存在

android - android.util.Log 中的错误或功能? - Log.isLoggable(DEBUG) = false 但 Log.d() 未禁用

Node.js - 记录/使用 morgan 和 winston

Node.js @google-cloud/logging-winston 在 GCE 实例中不工作

ajax - ExpressJS 后端挂起太多请求

logging - Graylog2- 如何将日志保留时间配置为 1 周

javascript - 使用 Winstonjs 记录器进行 Node 记录会出现 TypeError