Conditional Logger

Logger with conditional output based on environment and log levels

javascript (ES2020) 2025-11-12 logging debug utility conditional

Description

A logging utility that conditionally outputs logs based on environment settings and log levels. Supports different log levels (debug, info, warn, error) and can be enabled/disabled per level.

Features

  • Log level filtering
  • Environment-based enabling
  • Formatted output
  • Conditional logging

Code

RAW
const LOG_LEVELS = {  DEBUG: 0,  INFO: 1,  WARN: 2,  ERROR: 3};class Logger {  constructor(level = LOG_LEVELS.INFO, enabled = true) {    this.level = level;    this.enabled = enabled;  }    debug(...args) {    if (this.enabled && this.level <= LOG_LEVELS.DEBUG) {      console.log('[DEBUG]', ...args);    }  }    info(...args) {    if (this.enabled && this.level <= LOG_LEVELS.INFO) {      console.info('[INFO]', ...args);    }  }    warn(...args) {    if (this.enabled && this.level <= LOG_LEVELS.WARN) {      console.warn('[WARN]', ...args);    }  }    error(...args) {    if (this.enabled && this.level <= LOG_LEVELS.ERROR) {      console.error('[ERROR]', ...args);    }  }}module.exports = Logger;
RAW
const Logger = require('./logger');const logger = new Logger(1, true);logger.debug('Debug message');logger.info('Info message');logger.warn('Warning message');logger.error('Error message');if (false) {  logger.debug('This is a debug message');}

Comments

No comments yet. Be the first to comment!