【问题标题】:How to get node.js console.error and console.warn output in color如何以彩色获取 node.js console.error 和 console.warn 输出
【发布时间】:2018-05-30 15:19:50
【问题描述】:

有没有办法让 node.js 以彩色输出 console.error 和 console.warn 消息?

我希望我可以将所有 console.error 消息设为红色,将 console.warn 消息设为黄色,并将 console.log 消息设为默认颜色。

我四处寻找 node.exe 的命令行参数或环境变量选项,但我什么也没看到。也许彩色控制台消息是我必须选择不同的方式?

我想要一个适用于 Windows 10 的解决方案,以防万一。

【问题讨论】:

  • 您正在寻找日志或 ANSI 颜色库。
  • 可能有一个微妙但具体的区别:我希望为 console.error 的输出着色。
  • 您可以重新分配console 函数。
  • 有趣,@SLaks。我从来没有想过这样做。如果您使用示例代码将其写为答案,我会将其标记为这样。

标签: node.js


【解决方案1】:

您可以使用颜色包。

https://www.npmjs.com/package/colors

只需使用包装器来设置您想要的格式

module.exports = {
  error: message => console.log(message.red),
  warn: message => console.log(message.yellow),
}

您还可以使用像 pino 这样的日志库来为消息中的日志级别着色。

https://github.com/pinojs/pino

编辑:显示基本的记录器文件实现

我的自定义记录器.js

module.exports = {
  error: message => console.log(message.red),
  warn: message => console.log(message.yellow),
  info: message => console.log(message.green),
  debug: message => console.log(message.blue),
};

一些文件.js

const logger = require('./my-custom-logger);

logger.error('Something went very wrong');
logger.warn('I am just a warning');
logger.info('This is informational');
logger.debug('Let us dig a little deeper');

将其隐藏在您自己的 my-custom-logger.js 文件后面的好处在于,您可以在不更改所有代码的情况下在幕后换出实现。

我强烈建议深入研究 pino、bunyan 或 winston 作为日志框架。有很多好处,但我认为最大的 2 个是:

  1. 能够提高/降低日志级别以控制日志记录的详细程度
  2. 以 JSON 格式打印出对象,而不使用 JSON.stringify(object)

【讨论】:

  • 是的,我知道 colors 包。但我不知道如何将 colors 连接到 console.error、console.warn、console.log。
  • 为什么不把它隐藏在logging.js 文件后面?
  • 我不知道这意味着什么。我听到的是我可以需要一些自定义的 mylog 函数,然后是 mylog.error 或 mylog.warn 我的彩色输出方式。我想这已经足够好了。我只是不确定如何拦截现有的 console.* 调用。或者,如果这是可能的。
【解决方案2】:

您可以将console 中的方法设置为调用底层方法(您需要存储这些方法)的包装函数,但用颜色包装它们。

请注意,您也可以将对象传递给 console 方法,这会比较棘手。

const actualError = console.error;

console.error = function(...args) {
  actualError(...args.map(a => typeof a === 'string' ? colorize(a) : a);
};

【讨论】:

    猜你喜欢
    • 2021-03-12
    • 2013-09-28
    • 2011-12-16
    • 2017-07-23
    • 2016-04-10
    • 2011-05-17
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    相关资源
    最近更新 更多