98 lines
2.2 KiB
TypeScript
98 lines
2.2 KiB
TypeScript
import { type LogConfig } from "@/config.ts";
|
|
import * as log from "$std/log/mod.ts";
|
|
import { format } from "https://deno.land/std@0.163.0/node/util.ts";
|
|
|
|
export * as log from "$std/log/mod.ts";
|
|
|
|
const short: Record<number, string> = {
|
|
10: "DBG",
|
|
20: "INF",
|
|
30: "WRN",
|
|
40: "ERR",
|
|
50: "CRT",
|
|
};
|
|
|
|
const levelColors: Record<number, string> = {
|
|
10: "90",
|
|
20: "34",
|
|
30: "33",
|
|
40: "31",
|
|
50: "35",
|
|
};
|
|
|
|
const msgColors: Record<number, string> = {
|
|
40: "31",
|
|
50: "31",
|
|
};
|
|
|
|
class CustomConsoleHandler extends log.handlers.ConsoleHandler {
|
|
encoder: TextEncoder;
|
|
|
|
constructor(levelName: log.LevelName, options: log.HandlerOptions) {
|
|
super(levelName, options);
|
|
this.encoder = new TextEncoder();
|
|
}
|
|
|
|
override log(msg: string): Promise<number> {
|
|
const result = Deno.stdout.write(
|
|
this.encoder.encode(msg),
|
|
);
|
|
Deno.stdout.write(new Uint8Array([0x0a]));
|
|
return result;
|
|
}
|
|
}
|
|
|
|
export function setupLoggers(config: LogConfig, redact?: RegExp) {
|
|
// TODO: check support for colors and adjust as needed
|
|
log.setup({
|
|
handlers: {
|
|
console: new CustomConsoleHandler(
|
|
config.consoleLevelName,
|
|
{
|
|
formatter: ({ level, datetime, msg, args }: log.LogRecord) => {
|
|
let fullMessage = format(
|
|
msg,
|
|
...args,
|
|
);
|
|
if (redact) {
|
|
fullMessage = fullMessage.replaceAll(redact, "<REDACTED>");
|
|
}
|
|
return `\x1b[m[\x1b[${levelColors[level] || ""}m${
|
|
short[level] || "UNK"
|
|
}\x1b[m] \x1b[90m${datetime.toISOString()}\x1b[m \x1b[${
|
|
msgColors[level] || ""
|
|
}m${fullMessage}\x1b[m`;
|
|
},
|
|
},
|
|
),
|
|
},
|
|
loggers: {
|
|
default: {
|
|
level: "DEBUG",
|
|
handlers: ["console", "file"],
|
|
},
|
|
tasks: {
|
|
level: "ERROR",
|
|
handlers: ["console"],
|
|
},
|
|
},
|
|
});
|
|
|
|
/*
|
|
console.debug = log.debug;
|
|
console.info = log.info;
|
|
console.warn = log.warning;
|
|
console.error = log.error;
|
|
*/
|
|
|
|
/*
|
|
log.debug("Debug Log");
|
|
log.info("Info Log");
|
|
log.warning("Warning Log");
|
|
log.error("Error Log");
|
|
log.critical("Critical Log");
|
|
*/
|
|
|
|
log.info("Logger setup complete");
|
|
}
|