1

我有一个 winston 记录器,我想将执行记录器的文件的文件名设置为记录器信息对象的标签对象。例如:
[info]:[callingFileName.js] - 19.06.2019 14:09:19: [message]:...

这是我的代码:

'use strict';
const { createLogger, format, transports } = require('winston');
const winston = require('winston');
const path = require('path');
var appRoot = require('app-root-path');

const { splat, combine, timestamp, colorize, printf, label } = winston.format;

const o = {
  a: [1, 2, [[
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' +
      'eiusmod tempor incididunt ut labore et dolore magna aliqua.',
    'test',
    'foo']], 4],
  b: new Map([['za', 1], ['zb', 'test']])
};

var options = {
      debugfile: {
        level: 'debug',
        filename: `${appRoot}/logs/debug.log`,
        handleExceptions: true,
        json: true,
        maxsize: 5242880, // 5MB
        maxFiles: 5,
        colorize: false,
      },
      errorfile: {
        level: 'error',
        filename: `${appRoot}/logs/error.log`,
        handleExceptions: true,
        json: true,
        maxsize: 5242880, // 5MB
        maxFiles: 5,
        colorize: false,
      },
      console: {
        colorize: true,
        handleExceptions: true,
        prettyPrint: true,
        json: true,

      }
    };

    const customFormat = printf(info => `[${info.level}]:[${info.label}] - ${info.timestamp}: [message]: ${info.message}  ${info.meta? JSON.stringify(info.meta) : ''}`);


    const simplelogger = createLogger({
      name: "debug-console",
      format: combine(
        colorize({all:false}),
        timestamp({
          format: 'DD.MM.YYYY HH:mm:ss'
        }),
        label({ 
          label: path.basename(process.mainModule.filename) 
        }),
        splat(),
        customFormat
      ),
      transports: [
        new transports.Console(options.console),
        new transports.File( options.errorfile),
        new transports.File( options.debugfile)
      ]
    });

标签部分在这里:

label({ label: path.basename(process.mainModule.filename) }),

但我有一个问题,当我启动我的程序时,我运行npm run index.js,所以它总是将调用文件记录为 index.js 标签:[info]:[index.js] - 19.06.2019 14:09:19: [message]: ...。是否可以以某种方式将标签动态设置为我运行logger.log()函数的文件名?还是每次我在 index.js 以外的新文件中时都必须创建一个新的类/实例?

编辑:我切换到 npm logat 模块,它立即用 3 行代码解决了我的问题。但是,winston 有什么简单的解决方案吗?我刚刚看到我不再需要使用 logat 的 winston。

4

1 回答 1

0

标签用于静态文本,我认为没有简单的方法可以更改它。但是您可以在消息中定义文件名:

const customFormat = printf(info => 
   `[${info.level}]:[${path.basename(process.mainModule.filename)}] - ${info.timestamp}: [message]: ${info.message}  ${info.meta ? JSON.stringify(info.meta) : ''}`
);

const simplelogger = createLogger({
   name: "debug-console",
   format: combine(
      colorize({ all: false }),
      timestamp({ format: 'DD.MM.YYYY HH:mm:ss' }),
      splat(),
      customFormat
   ),
   transports: [
      new transports.Console(options.console),
      new transports.File(options.errorfile),
      new transports.File(options.debugfile)
   ]
});

你甚至可以修改日志信息,看这个例子:

const mutateMessage = format((info) => {
   if (info.sensitive) {
      info.message = info.message.replace(/root:.+@/, "root:[**REDACTED**]@");
   }
   if (/fail/i.test(info.message)) {
      info.level = 'error';
   }
   return info;
});


const logger = createLogger({
   level: 'info',
   format: combine(
      mutateMessage(),
      timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
      printf(({ message, timestamp, level }) => {
         return `${timestamp} [${level}] -> ${message}`;
      })
   ),
   transports: [
      new transports.Console()
   ],
});

logger.info(`Connect to mongodb://root:secret@localhost/admin?authSource=admin`, { sensitive: true });
logger.info('Authentication failed.');


2021-12-17 08:27:53.922 [info] -> Connect to mongodb://root:[**REDACTED**]@localhost/admin?authSource=admin
2021-12-17 08:27:53.925 [error] -> Authentication failed.
于 2021-12-17T07:29:59.490 回答