首页 > 解决方案 > 带有winston的aws cloudwatch控制台中出现的不是颜色,而是符号

问题描述

我正在使用 winston 进行日志记录,如下所示。

const winston = require('winston');
const {transports, format, createLogger  } = winston;
const { combine,errors, splat,timestamp } = format;

const logger = createLogger({
    level:  process.env.LOG_LEVEL,
    transports: [
        new transports.Console({
            format: combine(
                timestamp({
                    format: 'YYYY-MM-DD HH:mm:ss'
                }),
                errors({stack: true}),
                splat(),
                winston.format.colorize(),
                format.json()
            )
        })
    ]
});

module.exports = {logger};

并在控制台中显示符号而不是颜色,如下所示

{ 
"message": "apiKeyId: ef12dv3n3b", 
"level": "\u001b[34mdebug\u001b[39m",
"timestamp": "2019-08-20 07:07:16" 
}

我该如何解决?

标签: amazon-cloudwatchwinston

解决方案


我也一直在尝试从 NodeJS 输出到 Cloudwatch。并发现了同样的问题,根据我使用的组合,级别和/或消息会出现奇怪的字符编码。我认为这也是因为颜色。并发现了这个问题。

我猜你不能改变颜色。

我发现了一些 Chrome 扩展程序(未尝试过),例如“Colorize CloudWatch”,这可能是一种解决方法。我假设他们根据级别在浏览器中设置颜色。

我目前正在尝试 WinstonCloudwatch 传输而不是控制台(https://github.com/lazywithclass/winston-cloudwatch),到目前为止还没有看到字符编码问题。虽然从我所见,Cloudwatch仍然控制颜色,所以你得到一个标准的灰色/绿色 JSON。

这是我正在尝试的当前格式化程序(没有颜色),设置为messageFormatter: cloudwatchFormat

const cloudwatchFormat = function (info, opts) {
   const message = info.message;
   const splat = info[Symbol.for('splat')];
   const splatFormatted = splat ? splat.map((s) => (typeof s === 'string' ? s : JSON.stringify(s))) : '';

   return JSON.stringify({
      timestamp: new Date().toISOString(),
      level: info.level,
      message: message,
      variables: splatFormatted
   });
}

推荐阅读