All files / utils logger.ts

80% Statements 20/25
40% Branches 6/15
87.5% Functions 7/8
80% Lines 20/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77                                  4x             4x 98x 98x 98x   98x 98x     98x           4x 98x 98x     98x     4x 11x 11x     4x   86x                       1x           11x 11x      
/**
 * Debug logger that only outputs in development mode.
 * Controlled by VITE_DEBUG_LOGGING env variable.
 *
 * Usage:
 *   logger.debug('User logged in', { userId: 123 });
 *   logger.info('Processing complete');
 *   logger.warn('Deprecated API call');
 *   logger.error('Failed to fetch', error);
 */
type LogLevel = 'debug' | 'info' | 'warn' | 'error';
 
interface LoggerConfig {
	enabled: boolean;
	minLevel: LogLevel;
}
 
const LOG_LEVELS: Record<LogLevel, number> = {
	debug: 0,
	info: 1,
	warn: 2,
	error: 3
};
 
const getConfig = (): LoggerConfig => {
	const debugEnv: string = import.meta.env.VITE_DEBUG_LOGGING;
	const logLevel: string = import.meta.env.VITE_LOG_LEVEL;
	const isDev = import.meta.env.DEV;
 
	const isValidLogLevel = (level: string): level is LogLevel => {
		return ['debug', 'info', 'warn', 'error'].includes(level);
	};
 
	return {
		enabled: debugEnv === 'true' || (isDev && debugEnv !== 'false'),
		minLevel: isValidLogLevel(logLevel) ? logLevel : 'debug'
	};
};
 
const shouldLog = (level: LogLevel): boolean => {
	const config = getConfig();
	Iif (!config.enabled) {
		return false;
	}
	return LOG_LEVELS[level] >= LOG_LEVELS[config.minLevel];
};
 
const formatMessage = (level: LogLevel, message: string): string => {
	const timestamp = new Date().toISOString();
	return `[${timestamp}] [${level.toUpperCase()}] ${message}`;
};
 
export const logger = {
	debug: (message: string, ...args: unknown[]): void => {
		Iif (shouldLog('debug')) {
			console.warn(formatMessage('debug', message), ...args);
		}
	},
 
	info: (message: string, ...args: unknown[]): void => {
		if (shouldLog('info')) {
			console.warn(formatMessage('info', message), ...args);
		}
	},
 
	warn: (message: string, ...args: unknown[]): void => {
		Iif (shouldLog('warn')) {
			console.warn(formatMessage('warn', message), ...args);
		}
	},
 
	error: (message: string, ...args: unknown[]): void => {
		Eif (shouldLog('error')) {
			console.error(formatMessage('error', message), ...args);
		}
	}
} as const;