【问题标题】:Change bunyan log color for different levels更改不同级别的bunyan日志颜色
【发布时间】:2018-01-11 17:40:42
【问题描述】:

使用 Bunyan 时,我所有的日志级别都使用相同的青色,如下所示:

这是我们正在使用的 Bunyan 配置:

const bunyan = require('bunyan');
module.exports = bunyan.createLogger({name: 'cdt-api-server'});

我的问题是 - 如何让 Bunyan 使用红色或洋红色来记录错误信息/堆栈跟踪?问题是红色字符中的“ERROR”不足以引起我的注意 - 我希望整个堆栈都用红色或洋红色。

这是班扬自述文件: https://github.com/trentm/node-bunyan

我只看到提到过一次“颜色”。

我们可以这样做吗?

const bunyan = require('bunyan');

module.exports = bunyan.createLogger({
  name: 'cdt-api-server',
  streams: [
    {
      level: 'trace',
      stream: process.stdout,
      color: 'black',
    },
    {
      level: 'debug',
      stream: process.stdout,
      color: 'blue',
    },
    {
      level: 'info',
      stream: process.stdout,
      color: 'cyan',
    },
    {
      level: 'error',
      path: process.stderr,
      color: 'red'
    },
    {
      level: 'warn',
      path: process.stderr,
      color: 'magenta'
    }
  ]
});

【问题讨论】:

    标签: node.js logging error-logging bunyan


    【解决方案1】:

    使用 bunyan 进行日志记录时更改控制台输出颜色的一种方法是提供自定义流并将其与 colors 模块结合使用。

    以下示例将以蓝色输出信息日志,而以红色输出错误日志:

    var colors = require('colors');
    var bunyan = require('bunyan');
    
    function MyRawStream() {}
    MyRawStream.prototype.write = function (rec) {
        console.log('[%s] %s: %s',
            rec.time.toISOString(),
            bunyan.nameFromLevel[rec.level],
            rec.msg);
    }
    
    var log = bunyan.createLogger({
        name: 'play',
        streams: [
            {
                level: 'info',
                stream: new MyRawStream(),
                type: 'raw'
            }
        ]
    });
    
    log.info(colors.blue('This is an info message displayed in blue.'));
    log.error(colors.red('This is an error message displayed in red.'));
    
    /* Output:
    [2017-08-14T20:32:33.550Z] info: This is an info message displayed in blue.
    [2017-08-14T20:32:33.558Z] error: This is an error message displayed in red.
    */
    

    【讨论】:

    • 不使用console.log可能会覆盖write方法——如果我们在那里使用console.log似乎会不正确,不是吗?
    • 在后台,console.log() 使用格式化输出调用 process.stdout.write();后一个函数是 bunyan 默认为 info 日志级别使用的函数 - 请参阅 Streams Introduction。写到所说的函数是我让它工作的方式。如果您查看bunyan-format 的实现(这是建议的另一个模块),它们实际上会在内部调用formatRecord(),然后将输出发送到process.stdout。跨度>
    【解决方案2】:

    您可以检查bunyan-format 的颜色日志并在您的代码中执行相同的操作,或者将其作为模块导入并直接使用。

    【讨论】:

    • 什么是“这个模块”?
    • 鼓励链接到外部资源,但请在链接周围添加上下文,以便您的其他用户了解它是什么以及为什么存在。始终引用重要链接中最相关的部分,以防目标站点无法访问或永久离线。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 2017-08-24
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多