Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I skip writing log? level ignored? #394

Open
pquerner opened this issue Jul 24, 2024 · 0 comments
Open

How do I skip writing log? level ignored? #394

pquerner opened this issue Jul 24, 2024 · 0 comments

Comments

@pquerner
Copy link

My error level on winston is error.
I have transport for console, and 2 dailyRotation logs. 1 for debug. 1 for error.

The debug log is still written, ignoring the minimum level.

import winston from "winston";
import DailyRotateFile from 'winston-daily-rotate-file';
import fs from "fs";

export class Logger {
    private static logger: winston.Logger;

    public static getLogger() {
        try {
            if (typeof this.logger !== "undefined") {
                return this.logger;
            }
            const logger = Logger.buildLogger();
            this.logger = logger;
            return this.logger;
        } catch (error) {
            console.error(error);
        }
        return false;
    }

    public static log(level: string, msg: any) {
        if (this.getLogger() instanceof winston.Logger) {
            this.logger.log(level, msg);
            return;
        }
        console.log(msg);
    }

    private static getDirName() {
        const curDate = new Date();
        const curMonth = ("0" + (curDate.getMonth() + 1)).slice(-2);
        const curYYYYMM = curDate.getFullYear() + "-" + curMonth;
        return curYYYYMM;
    }

    private static getLogDir() {
        return `/var/log/myapp/123/`;
    }

    private static getRotationLogger(level: string) {
        const logsDirectory = Logger.getLogDir();
        const colorizer = Logger.getLoggerColorizer();
        let rotatingLog: DailyRotateFile = new DailyRotateFile({
            dirname: logsDirectory + Logger.getDirName(),
            filename: `%DATE%_${level}.log`,
            datePattern: 'YYYY-MM-DD',
            level: level,
            zippedArchive: true,
            maxSize: '20m',
            maxFiles: '14d',
            createSymlink: true,
            symlinkName: `current_${level}.log`,
            json: false,
            format: Logger.getLoggerFormat(colorizer)
        });

        rotatingLog.on('rotate', function () {
            if (!fs.existsSync(logsDirectory + Logger.getDirName() + '/')) {
                rotatingLog = new winston.transports.DailyRotateFile({
                    dirname: logsDirectory + Logger.getDirName(),
                    filename: `%DATE%_${level}.log`,
                    datePattern: 'YYYY-MM-DD',
                    level: level,
                });

            }
        });
        return rotatingLog;
    }

    private static buildLogger() {
        const colorizer = this.getLoggerColorizer();
        const logLevel = process.env.LOG_LEVEL || 'debug';
        const logger = winston.createLogger({
            level: logLevel,
            format: this.getLoggerFormat(colorizer),
            transports: [
                new (winston.transports.Console)(),
                Logger.getRotationLogger('error'),
                Logger.getRotationLogger('debug'),
            ],
        });
        return logger;
    }

    private static getLoggerColorizer() {
        const colorsConfig = {
            error: 'red',
            warn: 'yellow',
            info: 'green',
            debug: 'cyan'
        };

        const colorizer = winston.format.colorize({all: true, colors: colorsConfig});
        return colorizer;
    }

    private static getLoggerFormat(colorizer: winston.Logform.Colorizer) {
        return winston.format.combine(
            winston.format.timestamp(),
            winston.format.printf((meta: any) => {
                const {level, message, timestamp, namespace, stack, ...restMeta} = meta;
                let _message = message;
                if (meta.isSequelize) {
                    _message = 'Sequelize logging message:';
                    delete restMeta.isSequelize;
                }
                const _level = level || 'debug'
                const coloredLevel = colorizer.colorize(_level, `[${_level.toUpperCase()}]`);
                const displayNamespace = namespace ? `[${namespace}] -` : '';
                const stackMessage = stack ? `\n${stack}` : '';
                const otherMetaMessage = Object.keys(restMeta).length > 0 ? `\n${JSON.stringify(restMeta)}` : '';
                return `${timestamp} ${displayNamespace} ${coloredLevel}: ${_message} ${otherMetaMessage}${stackMessage}`;
            })
        );
    }
}

Call:

Logger.log('debug', 'foobar');.
I do not see the debug log in the console, but the file is written to %DATE%_debug.log (and symlinked to current_debug.log).

I expected the file not to be written at all, because my level doesnt match.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant