NodeJS 无法在winston中设置子记录器的日志级别

z9smfwbn  于 2023-08-04  发布在  Node.js
关注(0)|答案(2)|浏览(124)

我在node.js API中使用winston作为日志库。我为每个请求创建一个子日志记录器,其中包含一些默认的元数据,如请求ID和用户ID。
我希望只记录这些请求的info级别日志条目,这可以通过将日志记录器级别设置为info来实现,但是对于某些特定请求,例如特定用户的请求或传递参数时的请求,我希望在调试级别记录该子日志记录器
我尝试设置子记录器的level属性,但这被忽略,调试条目也不会被记录
下面是一个代码示例:

const winston = require('winston');

const mainLogger = winston.createLogger({
    transports: [
        new winston.transports.Console({
            format: winston.format.combine(
                winston.format.colorize(),
                winston.format.printf((info: any) => `[${info.timestamp}] ${info.level}: ${info.message}`)
            )
        })
    ],
    silent: false,
    level: 'info'
});

mainLogger.info('Info level');
mainLogger.error('Error');
mainLogger.debug('This should not be logged, and it is not. Good!');

const childLogger = mainLogger.child({ metadata: 'value' });
childLogger.level = 'debug';
childLogger.debug('This should be logged, but it is not. Bad!');

字符串
我该怎么做?我已经检查了所有的文档,但我只能看到关于调整主记录器和单个传输的级别的信息

7cjasjjr

7cjasjjr1#

我能够实现这一点唯一方法是创建一个logger类

const winston = require('winston');

class Logger {
    constructor(level = 'info', metadata = {}) {
        this.logger = winston.createLogger({
            transports: [
                new winston.transports.Console({
                    format: winston.format.combine(
                        winston.format.colorize(),
                        winston.format.printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`)
                    )
                })
            ],
            level,
            defaultMeta: metadata,
            silent: false
        });
    }

    log(level, message, metadata = {}) {
        this.logger.log(level, message, metadata);
    }

    info(message, metadata = {}) {
        this.logger.info(message, metadata);
    }

    error(message, metadata = {}) {
        this.logger.error(message, metadata);
    }

    debug(message, metadata = {}) {
        this.logger.debug(message, metadata);
    }

    // Add more log methods as needed, e.g., warn, verbose, etc.
}

// Main Logger
const mainLogger = new Logger('info');
mainLogger.info('Info level');
mainLogger.error('Error');
mainLogger.debug('This should not be logged, and it is not. Good!');

// Child Logger
const childLogger = new Logger('debug', { metadata: 'value' });
childLogger.info('This is a child logger info');
childLogger.error('This is a child logger error');
childLogger.debug('This is a child logger debug');

字符串

kzmpq1sx

kzmpq1sx2#

我相信在Winston中,每个日志记录器的日志级别是由主日志记录器的级别决定的,并且它不能在子日志记录器级别被覆盖。(我可能错了)
但是,您可以选择其他方法来实现您的目标。您可以使用自定义日志函数来检查特定条件,然后相应地进行日志记录,而不是直接更改子日志记录器的日志级别。就像这样

// ... (existing code)

const childLogger = mainLogger.child({ metadata: 'value' });

// Custom log function for the child logger
childLogger.customDebug = function (message, options) {
    if (options && (options.debugUser || options.logDebug)) {
        this.debug(message, options);
    }
};

childLogger.customDebug('This should be logged because of logDebug option.', { logDebug: true });
childLogger.customDebug('This should NOT be logged.');

字符串
也可以尝试根据自定义条件筛选日志级别。

// ... (existing code)
// Create a child logger
const childLogger = mainLogger.child({ metadata: 'value' });

// Log level for specific requests (e.g., user-specific or param-specific)
const DEBUG_LEVEL = 'customDebug';

// Log statements
mainLogger.info('Info level');
mainLogger.error('Error');
mainLogger.debug('This should not be logged, and it is not. Good!');

childLogger.log(DEBUG_LEVEL, 'This should be logged, and it is!');

// Log with custom message options
childLogger.log(DEBUG_LEVEL, 'This should also be logged with custom options.', { customDebug: true });


希望其中一个能为你工作。

相关问题