ls-deno/log.ts

98 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-11-09 16:55:27 -06:00
import { type LogConfig } from "@/config.ts";
2022-10-11 12:20:25 -05:00
import * as log from "$std/log/mod.ts";
2022-11-09 16:55:27 -06:00
import { format } from "https://deno.land/std@0.163.0/node/util.ts";
2022-10-11 12:20:25 -05:00
2022-10-11 16:17:21 -05:00
export * as log from "$std/log/mod.ts";
2022-11-09 16:55:27 -06:00
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;
}
}
2022-11-10 10:25:35 -06:00
export function setupLoggers(config: LogConfig, redact?: RegExp) {
// TODO: check support for colors and adjust as needed
2022-10-11 12:20:25 -05:00
log.setup({
handlers: {
2022-11-09 16:55:27 -06:00
console: new CustomConsoleHandler(
config.consoleLevelName,
{
formatter: ({ level, datetime, msg, args }: log.LogRecord) => {
2022-11-10 10:25:35 -06:00
let fullMessage = format(
2022-11-09 16:55:27 -06:00
msg,
2022-11-10 10:25:35 -06:00
...args,
2022-11-09 16:55:27 -06:00
);
2022-11-10 10:25:35 -06:00
if (redact) {
fullMessage = fullMessage.replaceAll(redact, "<REDACTED>");
}
2022-11-09 16:55:27 -06:00
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`;
},
},
),
2022-10-11 12:20:25 -05:00
},
loggers: {
default: {
level: "DEBUG",
handlers: ["console", "file"],
},
tasks: {
level: "ERROR",
handlers: ["console"],
},
},
});
2022-11-09 16:55:27 -06:00
/*
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");
2022-10-11 12:20:25 -05:00
}