import { ConsoleLogger, ConsoleLoggerOptions, LogLevel } from "@nestjs/common"; // eslint-disable-next-line @typescript-eslint/no-require-imports import createDebug = require("debug"); import { getTraceId } from "./trace-context"; /** Logger that routes all framework and application diagnostics through DEBUG. */ export class DebugLogger extends ConsoleLogger { private readonly loggerContext: string; constructor(context?: string, options: ConsoleLoggerOptions = {}) { super(context as string, options); this.loggerContext = context ?? "Application"; } override log(...args: Parameters): void { this.write("log", args); } override error(...args: Parameters): void { this.write("error", args); } override warn(...args: Parameters): void { this.write("warn", args); } override debug(...args: Parameters): void { this.write("debug", args); } override verbose(...args: Parameters): void { this.write("verbose", args); } override fatal(...args: Parameters): void { this.write("fatal", args); } private write(level: LogLevel, args: unknown[]): void { const [message, ...optionalParams] = args; const last = optionalParams[optionalParams.length - 1]; const lastIsErrorStack = level === "error" && optionalParams.length === 1 && typeof last === "string" && /(?:\n|^\s*at\s)/.test(last); const context = typeof last === "string" && !lastIsErrorStack ? last : this.loggerContext; const details = typeof last === "string" && !lastIsErrorStack ? optionalParams.slice(0, -1) : optionalParams; const traceId = getTraceId(); const tracedContext = traceId ? `${context}:${traceId}` : context; const namespace = process.env.NODE_ENV === "test" ? "test" : `liqa:${context.toLowerCase()}`; const stringify = (value: unknown): string => { if (value instanceof Error) return value.stack ?? value.message; if (typeof value === "string") return value; try { return JSON.stringify(value); } catch { return String(value); } }; const output = `[${level.toUpperCase()}] [${tracedContext}] ${stringify(message)}${details.length ? ` ${details.map(stringify).filter(Boolean).join(" ")}` : ""}`; createDebug(namespace)("%s", output); } }