首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >winston自定义日志颜色

winston自定义日志颜色
EN

Stack Overflow用户
提问于 2019-12-18 20:01:38
回答 1查看 1.6K关注 0票数 1

我想创建自定义日志级别。创建是正确的,我可以在将来使用它们,但当我使用自定义关卡时,消息不会着色。正如我所看到的-颜色是在关卡之前添加的,这就是为什么我不能在自定义关卡中使用颜色。我的代码如下,当我使用warn或custom时-它崩溃并返回错误:

代码语言:javascript
复制
TypeError: colors[Colorizer.allColors[lookup]] is not a function

还有调用的代码:

代码语言:javascript
复制
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');

和logger.js

代码语言:javascript
复制
const winston = require('winston');
const colorizer = winston.format.colorize();
const {
  combine, timestamp, printf, simple,
} = winston.format;

const myCustomLevels = {
  levels: {
    error: 0,
    warn: 1,
    data: 2,
    info: 3,
    debug: 4,
    verbose: 5,
    silly: 6,
    custom: 7,
  },
  colors: {
    error: 'red',
    warn: 'orange',
    data: 'grey',
    info: 'green',
    debug: 'yellow',
    verbose: 'cyan',
    silly: 'magenta',
    custom: 'blue',
  },
};

colorizer.addColors(myCustomLevels.colors);

const logger = winston.createLogger({
  colorize: true,
  prettyPrint: true,
  level: 'custom',
  levels: myCustomLevels.levels,
  format: combine(
    simple(),
    printf(
      (msg) => {
        return colorizer.colorize(
          msg.level,
          `${msg.level} - ${msg.message}`,
        );
      },
    ),
    timestamp(),
  ),
  transports: [
    new winston.transports.Console(),
  ],
});

module.exports = logger;

如何在自定义关卡中使用colorize?

EN

回答 1

Stack Overflow用户

发布于 2019-12-18 20:37:45

Usnig colorize:true会破坏你的自定义格式,如果你想给你所有的日志文本上色,你可以像这样手动完成:

代码语言:javascript
复制
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函数中使用:

代码语言:javascript
复制
levels: myLevels,
format: combine(
winston.format.prettyPrint(),
winston.format.metadata(),
winston.format.json(),
label({ label }),
timestamp(),
myFormat
),
.
.
.
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59391618

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档