/
logger.ts
80 lines (69 loc) 路 1.88 KB
/
logger.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
import {
bold,
brightGreen,
dim,
red,
strikethrough,
yellow,
} from "../deps/colors.ts";
import type { ErrorData, Page } from "../core.ts";
export interface Options {
/** Set to true to disable logging. */
quiet: boolean;
}
/**
* Class to output messages to the console.
* If quiet mode is enabled, no messages will be output.
*/
export default class Logger {
quiet: boolean;
formats: Record<string, (str: string) => string> = {
red,
Red: (str: string) => bold(red(str)),
dim,
Dim: (str: string) => bold(dim(str)),
green: brightGreen,
Green: (str: string) => bold(brightGreen(str)),
yellow: yellow,
Yellow: (str: string) => bold(yellow(str)),
del: (str: string) => strikethrough(dim(str)),
};
constructor(options: Options) {
this.quiet = options.quiet;
}
/**
* Outputs a message to the console.
* You can use html tags in the message for colors.
* For example: `logger.log("<red>Hello World!</red>")`
*/
log(...messages: unknown[]): void {
if (this.quiet) {
return;
}
const format = messages.map((message) =>
typeof message === "string"
? message.replaceAll(
/<(\w+)>([^<]+)<\/\1>/g,
(_, name, content) => this.formats[name]!(content),
)
: message
);
console.log(...format);
}
/** Shows a warning message */
warn(message: string, data: ErrorData = {}) {
const name = data.name || "Warning";
delete data.name;
this.log(`鈿狅笍 <Yellow>${name}</Yellow> ${message}`);
for (let [key, value] of Object.entries(data ?? {})) {
if (key === "page") {
value = (value as Page).src.path + (value as Page).src.ext;
} else if (value instanceof Error) {
value = value.toString();
} else if (value instanceof URL) {
value = value.toString();
}
this.log(` <dim>${key}</dim>:`, value);
}
}
}