53 lines
1.4 KiB
JavaScript
53 lines
1.4 KiB
JavaScript
import process from 'process';
|
|
|
|
const LOG_LEVELS = {
|
|
debug: 0,
|
|
info: 1,
|
|
warn: 2,
|
|
error: 3
|
|
};
|
|
|
|
const currentLevelStr = (process.env.LOG_LEVEL || 'info').toLowerCase();
|
|
const currentLevel = LOG_LEVELS[currentLevelStr] !== undefined ? LOG_LEVELS[currentLevelStr] : 1;
|
|
|
|
const ANSI_COLORS = {
|
|
DEBUG: '\x1b[36mDEBUG\x1b[0m', // Cyan
|
|
INFO: '\x1b[32mINFO\x1b[0m', // Green
|
|
WARN: '\x1b[33mWARN\x1b[0m', // Yellow
|
|
ERROR: '\x1b[31mERROR\x1b[0m' // Red
|
|
};
|
|
|
|
/**
|
|
* Helper to print log structured JSON objects to stdout.
|
|
* @param {string} levelName
|
|
* @param {string} eventName
|
|
* @param {object} [attributes]
|
|
*/
|
|
function writeLog(levelName, eventName, attributes = {}) {
|
|
const levelNum = LOG_LEVELS[levelName];
|
|
if (levelNum < currentLevel) {
|
|
return;
|
|
}
|
|
|
|
const levelUpper = levelName.toUpperCase();
|
|
const logEntry = {
|
|
timestamp: new Date().toISOString(),
|
|
level: `__COLOR_LEVEL_${levelUpper}__`,
|
|
event: eventName,
|
|
...attributes
|
|
};
|
|
|
|
let jsonStr = JSON.stringify(logEntry);
|
|
const coloredLevel = ANSI_COLORS[levelUpper] || levelUpper;
|
|
jsonStr = jsonStr.replace(`"__COLOR_LEVEL_${levelUpper}__"`, `"${coloredLevel}"`);
|
|
|
|
process.stdout.write(jsonStr + '\n');
|
|
}
|
|
|
|
export const logger = {
|
|
debug: (event, attrs) => writeLog('debug', event, attrs),
|
|
info: (event, attrs) => writeLog('info', event, attrs),
|
|
warn: (event, attrs) => writeLog('warn', event, attrs),
|
|
error: (event, attrs) => writeLog('error', event, attrs)
|
|
};
|