JavaScript 使用新的日志级别修改 winston-logger

JavaScript modify winston-logger with a new log-level

我对 logger 模块 winston 进行了优化,不知道如何添加新的 loglevel

也许您想知道我需要它做什么。我需要这个用于 API 数据库查询。

我的记录器的一个例子是:

logger.info('I am a Log');

20220202.163730-[m295] info: POST /v1/authenticate 401 45- 423.099 ms

并希望使用名为 'front'

的自定义日志级别进行记录

例如:

logger.front('I am a Log');

20220202.163730-[m295] front: POST /v1/authenticate 401 45- 423.099ms

来自模块的代码:

const { createLogger, format, transports } = require('winston');
const env = process.env.NODE_ENV || 'development';
const defaultFormat = format.combine(
  format.splat(),
  format.label({ label: '[m295]' }),
  format.timestamp({ format: 'YYYYMMDD.HHmmss' }),
  format.printf((info) => {
    if (info instanceof Error) {
      info.message = info.stack;
    }
    if (typeof info.message === 'object') {
      info.message = JSON.stringify(info.message, null, 2);
    }
    return `${info.timestamp} - ${info.label} ${info.level}: ${info.message}`;
  }),
);
const logger = createLogger({
  level: 'info',
  format: format.combine(
    format.splat(),
    format.label({ label: '[m295]' }),
    format.timestamp({ format: 'YYYYMMDD.HHmmss' }),
    format.printf(
      (info) =>
        `${info.timestamp} - ${info.label} ${info.level}: ${info.message}`,
    ),
  ),
  transports: [
    new transports.File({ filename: './logs/error.log', level: 'error' }),
    new transports.File({ filename: './logs/server.log' }),
    new transports.File({ filename: './logs/front.log', level: 'front' }),
  ],
  exceptionHandlers: [
    new transports.File({
      filename: './logs/exceptions.log',
      timestamp: true,
      maxsize: 1000000,
    }),
  ],
});

logger.stream = {
  write: function (message, encoding) {
    logger.info(message.replace(/\n$/, ''));
  },
};

if (env !== 'development') {
  logger.add(
    new transports.Console({
      format: format.combine(
        format.colorize(),
        format.splat(),
        format.label({ label: 'm295' }),
        format.timestamp({ format: 'YYYYMMDD.HHmmss' }),
        format.printf(
          (info) =>
            `${[info.timestamp]} - ${info.level}: ${info.message} [${
              info.label
            }]`,
        ),
      ),
    }),
  );
}

module.exports = logger;

使用代码:

const logger = require('../utils/logger');
logger.info('I am a log'); //or
logger.log('info','I am a log');

我可以做个日志吗

我想做一个这样的日志级别的日志:

const logger = require('../utils/logger');
logger.front('I am a log'); //or
logger.log('front','I am a log');
``
Can somebody help me? thanks

custom-levels 可能这就是您要找的。

const myCustomLevels = {
  levels: {
    foo: 0,
    bar: 1,
    baz: 2,
    foobar: 3
  },
  colors: {
    foo: 'blue',
    bar: 'green',
    baz: 'yellow',
    foobar: 'red'
  }
};

const customLevelLogger = winston.createLogger({
  level: 'foobar',
  levels: myCustomLevels.levels,
  transports: [
    new winston.transports.Console()
  ]
});