From f4aff7d6f1879c1a3486995c8d9c863a51c5d47a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lud=C4=9Bk=20Nov=C3=BD?= <13610612+ludeknovy@users.noreply.github.com> Date: Wed, 11 Dec 2024 08:29:57 +0100 Subject: [PATCH] Add dynamic log level configuration with environment variable --- src/logger.ts | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/src/logger.ts b/src/logger.ts index b45f089..45026cb 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -1,10 +1,32 @@ import * as winston from "winston" +const LOG_LEVELS = winston.config.syslog.levels +const DEFAULT_LOG_LEVEL = "debug" + +const getLogLevel = (): string => { + const logLevelEnvVar = process.env.LOG_LEVEL + if (logLevelEnvVar) { + const isAllowedLogLevel = Object.keys(LOG_LEVELS) + .find(level => logLevelEnvVar.toLowerCase() === level.toLowerCase()) + if (!isAllowedLogLevel) { + console.log("Unsupported log level: ", logLevelEnvVar) + } else { + return isAllowedLogLevel + } + } + return DEFAULT_LOG_LEVEL + + +} + export const logger = winston.createLogger({ - format: winston.format.combine( - winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }), - winston.format.json() - ), - levels: winston.config.syslog.levels, - transports: [ new winston.transports.Console() ], + format: winston.format.combine( + winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }), + winston.format.json() + ), + level: getLogLevel(), + levels: LOG_LEVELS, + transports: [new winston.transports.Console()], }) + +