You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Winston http日志级别行为与info不一致 输出含undefined

问题原因

日志里http级别输出携带的undefined是winston.format.cli()格式化器的内置配置缺失导致的,和Node.js版本、Express框架逻辑无关:

  • cli格式化器内部维护了一份日志级别和终端显示颜色的映射表,默认仅覆盖error、warn、info、verbose、debug、silly六个标准npm日志级别,没有预置http级别的颜色配置
  • 格式化器拼接日志前缀时,会读取对应级别的颜色渲染函数处理前缀文本,读取http级别的配置时拿到的返回值为undefined,直接和前缀、日志正文拼接后就输出了http:undefined⟵ 日志内容的异常结果
  • 你看到单请求触发多组重复日志是浏览器访问站点时会自动请求/、/favicon.ico等路径,每个请求都会进入你注册的日志中间件,属于正常表现,和该undefined问题无关。
修复方法

任选一种方案即可解决问题:

  • 方案1:初始化cli格式化器时手动补全http级别的颜色配置
new winston.transports.Console({
  format: winston.format.combine(
    winston.format.errors({ stack: true }),
    winston.format.timestamp(),
    winston.format.cli({
      colors: {
        error: 'red',
        warn: 'yellow',
        info: 'green',
        http: 'magenta',
        verbose: 'cyan',
        debug: 'blue',
        silly: 'grey'
      }
    }),
  ),
}),
  • 方案2:放弃cli格式化器,自行组合colorize和printf格式化器自定义输出格式,可控性更高
new winston.transports.Console({
  format: winston.format.combine(
    winston.format.errors({ stack: true }),
    winston.format.timestamp(),
    winston.format.colorize({ all: true }),
    winston.format.printf(({ level, message, timestamp, stack }) => {
      return stack ? `${timestamp} ${level}: ${message}\n${stack}` : `${timestamp} ${level}: ${message}`
    })
  ),
}),
  • 方案3:将winston升级到已补全该默认配置的最新稳定版本,无需修改原有代码即可正常输出http级别日志。

内容的提问来源于stack exchange,提问作者Miaucl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 13:06:25