43 lines
1.1 KiB
JavaScript
43 lines
1.1 KiB
JavaScript
// Structured JSON logger with traceId support
|
|
import { randomUUID } from "crypto";
|
|
|
|
const LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
|
|
const CURRENT_LEVEL = LOG_LEVELS[process.env.LOG_LEVEL || "info"] ?? LOG_LEVELS.info;
|
|
|
|
function formatLog(level, message, data = {}) {
|
|
const entry = {
|
|
ts: new Date().toISOString(),
|
|
level,
|
|
msg: message,
|
|
...data,
|
|
};
|
|
if (!entry.traceId) {
|
|
entry.traceId = randomUUID().slice(0, 8);
|
|
}
|
|
return JSON.stringify(entry);
|
|
}
|
|
|
|
function createLogger(module) {
|
|
function log(level, message, data = {}) {
|
|
if (LOG_LEVELS[level] < CURRENT_LEVEL) return;
|
|
const line = formatLog(level, message, { module, ...data });
|
|
if (level === "error") {
|
|
console.error(line);
|
|
} else if (level === "warn") {
|
|
console.warn(line);
|
|
} else {
|
|
console.log(line);
|
|
}
|
|
}
|
|
|
|
return {
|
|
debug: (msg, data) => log("debug", msg, data),
|
|
info: (msg, data) => log("info", msg, data),
|
|
warn: (msg, data) => log("warn", msg, data),
|
|
error: (msg, data) => log("error", msg, data),
|
|
child: (extra) => createLogger(`${module}:${extra.sub || "child"}`),
|
|
};
|
|
}
|
|
|
|
export { createLogger };
|