-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
102 lines (87 loc) · 2.15 KB
/
mod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// deno-lint-ignore-file no-explicit-any
import { bold, cyan, gray, italic, red, yellow } from "../../deps.ts";
export enum LogLevels {
Debug,
Info,
Warn,
Error,
Fatal,
}
const prefixes = new Map<LogLevels, string>([
[LogLevels.Debug, "DEBUG"],
[LogLevels.Info, "INFO"],
[LogLevels.Warn, "WARN"],
[LogLevels.Error, "ERROR"],
[LogLevels.Fatal, "FATAL"],
]);
const noColor: (str: string) => string = (msg) => msg;
const colorFunctions = new Map<LogLevels, (str: string) => string>([
[LogLevels.Debug, gray],
[LogLevels.Info, cyan],
[LogLevels.Warn, yellow],
[LogLevels.Error, (str: string) => red(str)],
[LogLevels.Fatal, (str: string) => red(bold(italic(str)))],
]);
export function logger({
logLevel = LogLevels.Info,
name,
}: {
logLevel?: LogLevels;
name?: string;
} = {}) {
function log(level: LogLevels, ...args: any[]) {
if (level < logLevel) return;
let color = colorFunctions.get(level);
if (!color) color = noColor;
const date = new Date();
const log = [
`[${date.toLocaleDateString()} ${date.toLocaleTimeString()}]`,
color(prefixes.get(level) || "DEBUG"),
name ? `${name} >` : ">",
...args,
];
switch (level) {
case LogLevels.Debug:
return console.debug(...log);
case LogLevels.Info:
return console.info(...log);
case LogLevels.Warn:
return console.warn(...log);
case LogLevels.Error:
return console.error(...log);
case LogLevels.Fatal:
return console.error(...log);
default:
return console.log(...log);
}
}
function setLevel(level: LogLevels) {
logLevel = level;
}
function debug(...args: any[]) {
log(LogLevels.Debug, ...args);
}
function info(...args: any[]) {
log(LogLevels.Info, ...args);
}
function warn(...args: any[]) {
log(LogLevels.Warn, ...args);
}
function error(...args: any[]) {
log(LogLevels.Error, ...args);
}
function fatal(...args: any[]) {
log(LogLevels.Fatal, ...args);
}
return {
log,
setLevel,
debug,
info,
warn,
error,
fatal,
};
}
export const log = logger({ name: "Main" });
export default log;