温斯顿自定义日志颜色

时间:2019-12-18 12:01:37

标签: node.js logging winston colorize

我想创建自定义日志级别。创建是正确的,以后我可以使用它们,但是当我使用自定义级别时,消息不会变色。如我所见-颜色是在级别之前添加的,这就是为什么我不能将颜色用于自定义级别。我的代码在下面,当我使用警告或自定义时-它因错误而崩溃:

const target = e.originalEvent.toElement.closest('tr');
if (target && target.id) {
  const td = target.querySelector('td:nth-child(2)');
  const fieldValue = e.data[target.id];
  if (td) {
    console.log("This row ID is =" + td.value)
  }
}

调用的代码:

TypeError: colors[Colorizer.allColors[lookup]] is not a function

和logger.js

const Winston = require('./logger');
Winston.error('1 This is a info statement');
Winston.data('2 This is a warning statement');
Winston.info('3 This is a warning statement');
Winston.debug('4 This is a error statement');
Winston.verbose('6 This is a warning statement');
Winston.silly('7 This is a error statement');
Winston.warn('5 This is a debug statement');
Winston.custom('8 This is a error statement');

如何在自定义级别上使用着色?

1 个答案:

答案 0 :(得分:1)

Usnig colorize:true将破坏您的自定义格式,如果您希望为所有日志文本加上颜色,则可以手动执行以下操作:

const { combine, timestamp, label, printf } = winston.format;
const color = {
'info': "\x1b[36m",
'error': "\x1b[31m",
'warn': "\x1b[33m"
.
.
.
};
const myFormat = printf(({ level, message, label, timestamp }) => {
return `${level}: ${color[level] || ''} ${label} || ${timestamp} || ${message}\x1b[0m `;
});

然后在createLogger函数中使用它:

levels: myLevels,
format: combine(
winston.format.prettyPrint(),
winston.format.metadata(),
winston.format.json(),
label({ label }),
timestamp(),
myFormat
),
.
.
.