Files
fredy/lib/services/logger.js

67 lines
1.7 KiB
JavaScript
Raw Normal View History

2025-09-14 10:32:39 +02:00
const COLORS = {
debug: '\x1b[36m',
info: '\x1b[32m',
warn: '\x1b[33m',
error: '\x1b[31m',
reset: '\x1b[0m',
};
2025-09-13 18:57:56 +02:00
2025-09-14 10:40:18 +02:00
const env = process.env.NODE_ENV || 'development';
2025-09-14 10:32:39 +02:00
const useColor = process.stdout.isTTY || process.stderr.isTTY;
2025-09-13 18:57:56 +02:00
2025-09-14 10:32:39 +02:00
function ts() {
const d = new Date();
const yyyy = d.getFullYear();
const mm = String(d.getMonth() + 1).padStart(2, '0');
const dd = String(d.getDate()).padStart(2, '0');
const hh = String(d.getHours()).padStart(2, '0');
const mi = String(d.getMinutes()).padStart(2, '0');
const ss = String(d.getSeconds()).padStart(2, '0');
return `${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss}`;
}
2025-09-13 18:57:56 +02:00
2025-09-14 10:32:39 +02:00
function lvl(level) {
const upper = level.toUpperCase();
if (!useColor) return upper;
return `${COLORS[level] || ''}${upper}${COLORS.reset}`;
}
/* eslint-disable no-console */
function log(level, ...args) {
2025-09-14 10:40:18 +02:00
if (level === 'debug' && env !== 'development') {
return; // Skip debug logs in non-development environments
}
2025-09-14 10:32:39 +02:00
const prefix = `[${ts()}] ${lvl(level)}:`;
switch (level) {
case 'debug':
console.debug(prefix, ...args);
break;
case 'info':
console.info(prefix, ...args);
break;
case 'warn':
console.warn(prefix, ...args);
break;
case 'error':
console.error(prefix, ...args);
break;
default:
console.log(prefix, ...args);
}
}
export default {
debug: (...a) => log('debug', ...a),
info: (...a) => log('info', ...a),
warn: (...a) => log('warn', ...a),
error: (...a) => log('error', ...a),
};
// Beispiel:
// import logger from './logger.js';
// const a = 'fick';
// const b = { tr: 'lolo' };
// logger.info('hallo', a, b);
// -> In IntelliJ siehst du das Objekt wie bei console.info, plus Prefix