-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging.ts
More file actions
69 lines (59 loc) · 2.01 KB
/
logging.ts
File metadata and controls
69 lines (59 loc) · 2.01 KB
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
interface Stringifiable { toString: () => string }
type LoggingFunction<T> = (...args: Stringifiable[]) => T
const LEVEL_TO_CONSOLE: Record<LogLevel, () => (...args: unknown[]) => void> = {
internal: () => console.trace,
trace: () => console.trace,
debug: () => console.debug,
info: () => console.log,
warn: () => console.warn,
error: () => console.error,
fatal: () => console.error
}
const LEVEL_TO_NUMBER: Record<LogLevel, number> = {
internal: 0,
trace: 1,
debug: 10,
info: 20,
warn: 30,
error: 40,
fatal: 50
}
/**
* The levels which a {@link Logger} can operate at.
*/
export type LogLevel = 'internal' | 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'
/**
* The logging class used internally to (configurably) inform users about library behaviour.
* This is a thin wrapper around the {@link console}, and should generally be set to something above 'info' in production.
*/
export class Logger {
internal = this.makeLevelFunc('internal', false)
trace = this.makeLevelFunc('trace', false)
debug = this.makeLevelFunc('debug', false)
info = this.makeLevelFunc('info', false)
warn = this.makeLevelFunc('warn', false)
error = this.makeLevelFunc('error', false)
fatal = this.makeLevelFunc('fatal', true)
private level: LogLevel = 'info'
constructor (public readonly name: string) {}
setLevel (level: LogLevel): this {
this.level = level
return this
}
private makeLevelFunc (level: LogLevel, exit: true): LoggingFunction<never>
private makeLevelFunc (level: LogLevel, exit: false): LoggingFunction<void>
private makeLevelFunc (level: LogLevel, exit: boolean): LoggingFunction<void> {
return (...args) => {
const ourLevel = LEVEL_TO_NUMBER[this.level]
const targetLevel = LEVEL_TO_NUMBER[level]
if (ourLevel > targetLevel) {
return
}
const fn = LEVEL_TO_CONSOLE[level]()
fn(`[${level.toUpperCase()}]`.padEnd(7), `[${this.name}]`, new Date().toISOString(), ':', ...args)
if (exit) {
process.exit()
}
}
}
}