Conditional Logger
Logger with conditional output based on environment and log levels
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
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;
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!
Please login to leave a comment.