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

如何在JavaScript控制台保留默认语法高亮颜色?

问题:Winston日志丢失默认console.log的类型颜色区分

默认的console.log会根据值的类型(比如string或number)自动区分颜色,如图中绿色箭头所示:
默认console.log的颜色区分
但使用Winston格式化日志时,红色箭头处显示这类颜色区分功能丢失了。

初始尝试代码

function getArgumentsPreserved(providedArguments: Arguments): string {
  // 参考util.inspect用法
  // 参考chalk相关问题
  return util.inspect(providedArguments, { colors: false, depth: null });
}

const simpleConsoleLogging = winston.format.combine(
  // 本地环境的简易控制台日志配置
  winston.format.timestamp(),
  winston.format.printf((info) => {
    const { level, message, timestamp, ...rest } = info;
    const coloredTimestampAndLevel = colorizer.colorize(level, `${timestamp} ${level}:`);

    //const syntaxHighlightedObjects = Object.keys(rest).length > 0 ? getArgumentsPreserved(rest) : '';
    const syntaxHighlightedObjects = Object.keys(rest).length > 0 ? JSON.stringify(rest) : ''; // TODO: 如何恢复console.log默认的语法着色功能?
    return `${coloredTimestampAndLevel} ${message} ${syntaxHighlightedObjects}`;
  }),
);

尝试使用util.inspect但未成功。

更新:接近实现但丢失键名

现在的版本已接近需求,但截图显示'abc'和'def'这类键名丢失了:
更新后的问题截图

更新后的代码

function getArgumentsPreserved(providedArguments: Arguments): string {
  if (Object.keys(providedArguments).length > 0) {
    const copiedArr = getRealKeys(providedArguments);
    // 参考util.inspect用法
    // 参考chalk相关问题
    return util.inspect(copiedArr, { colors: true, depth: null });
  } else {
    return '';
  }
}

function getRealKeys(rest: Arguments) {
  const result: string[] = [];
  Object.keys(rest).forEach(key => {
    result.push(rest[key])
  })
  return result;
}

const simpleConsoleLogging = winston.format.combine(
  // 本地环境的简易控制台日志配置
  winston.format.timestamp(),
  winston.format.printf((info) => {
    const { level, message, timestamp, ...rest } = info;
    const coloredTimestampAndLevel = colorizer.colorize(level, `${timestamp} ${level}:`);

    const syntaxHighlightedObjects = getArgumentsPreserved(rest);
    return `${coloredTimestampAndLevel} ${message} ${syntaxHighlightedObjects}`;
  }),
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:15:41