memorium/lib/log.ts

61 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-08-17 21:38:08 +02:00
import { EventEmitter } from "https://deno.land/x/evtemitter@v3.0.0/mod.ts";
import { LOG_LEVEL as _LOG_LEVEL } from "@lib/env.ts";
2023-08-13 02:26:22 +02:00
2023-08-05 22:16:14 +02:00
enum LOG_LEVEL {
2023-08-13 02:26:22 +02:00
DEBUG = 0,
INFO = 1,
WARN = 2,
ERROR = 3,
2023-08-05 22:16:14 +02:00
}
2023-08-16 23:51:56 +02:00
const logMap = {
2023-08-17 21:38:08 +02:00
"debug": LOG_LEVEL.DEBUG,
"info": LOG_LEVEL.INFO,
"warn": LOG_LEVEL.WARN,
"error": LOG_LEVEL.ERROR,
} as const;
2023-08-16 23:51:56 +02:00
2023-08-13 02:26:22 +02:00
const logFuncs = {
[LOG_LEVEL.DEBUG]: console.debug,
[LOG_LEVEL.INFO]: console.info,
[LOG_LEVEL.WARN]: console.warn,
[LOG_LEVEL.ERROR]: console.error,
} as const;
2023-08-05 22:16:14 +02:00
let longestScope = 0;
let logLevel = (_LOG_LEVEL && _LOG_LEVEL in logMap && logMap[_LOG_LEVEL]) ??
2023-08-17 21:38:08 +02:00
LOG_LEVEL.WARN;
2023-08-05 22:16:14 +02:00
2023-08-13 02:26:22 +02:00
const ee = new EventEmitter<{
log: { level: LOG_LEVEL; scope: string; args: unknown[] };
}>();
2023-08-05 22:16:14 +02:00
export function setLogLevel(level: LOG_LEVEL) {
logLevel = level;
}
type LoggerOptions = {
enabled?: boolean;
};
2023-08-13 02:26:22 +02:00
const createLogFunction =
(scope: string, level: LOG_LEVEL) => (...data: unknown[]) => {
ee.emit("log", { level, scope, args: data });
if (level <= logLevel) return;
logFuncs[level](`[${scope.padEnd(longestScope, " ")}]`, ...data);
};
2023-08-05 22:16:14 +02:00
export function createLogger(scope: string, _options?: LoggerOptions) {
longestScope = Math.max(scope.length, longestScope);
return {
2023-08-13 02:26:22 +02:00
debug: createLogFunction(scope, LOG_LEVEL.DEBUG),
info: createLogFunction(scope, LOG_LEVEL.INFO),
error: createLogFunction(scope, LOG_LEVEL.ERROR),
warn: createLogFunction(scope, LOG_LEVEL.WARN),
addEventListener:
((type, cb) =>
ee.addEventListener(type, cb)) as typeof ee.addEventListener,
2023-08-05 22:16:14 +02:00
};
}