-
-
Notifications
You must be signed in to change notification settings - Fork 492
/
DefaultLogger.ts
92 lines (73 loc) · 2.45 KB
/
DefaultLogger.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
import type { Logger, LoggerNamespace, LogContext, LoggerOptions } from './Logger';
import { colors } from './colors';
export class DefaultLogger implements Logger {
public debugMode = this.options.debugMode ?? false;
readonly writer = this.options.writer;
private readonly usesReplicas = this.options.usesReplicas;
private readonly highlighter = this.options.highlighter;
constructor(private readonly options: LoggerOptions) {}
/**
* @inheritDoc
*/
log(namespace: LoggerNamespace, message: string, context?: LogContext): void {
if (!this.isEnabled(namespace)) {
return;
}
// clean up the whitespace
message = message.replace(/\n/g, '').replace(/ +/g, ' ').trim();
// use red for error levels
if (context?.level === 'error') {
message = colors.red(message);
}
// use yellow for warning levels
if (context?.level === 'warning') {
message = colors.yellow(message);
}
const label = context?.label
? colors.cyan(`(${context.label}) `)
: '';
this.writer(colors.grey(`[${namespace}] `) + label + message);
}
/**
* @inheritDoc
*/
error(namespace: LoggerNamespace, message: string, context?: LogContext): void {
this.log(namespace, message, { ...context, level: 'error' });
}
/**
* @inheritDoc
*/
warn(namespace: LoggerNamespace, message: string, context?: LogContext): void {
this.log(namespace, message, { ...context, level: 'warning' });
}
/**
* @inheritDoc
*/
setDebugMode(debugMode: boolean | LoggerNamespace[]): void {
this.debugMode = debugMode;
}
isEnabled(namespace: LoggerNamespace): boolean {
return !!this.debugMode && (!Array.isArray(this.debugMode) || this.debugMode.includes(namespace));
}
/**
* @inheritDoc
*/
logQuery(context: { query: string } & LogContext): void {
if (!this.isEnabled('query')) {
return;
}
/* istanbul ignore next */
let msg = this.highlighter?.highlight(context.query) ?? context.query;
if (context.took != null) {
if (context.results != null) {
msg += colors.grey(` [took ${context.took} ms, ${context.results} result${context.results > 1 ? 's' : ''}]`);
} else {
msg += colors.grey(` [took ${context.took} ms]`);
}
}
if (this.usesReplicas && context.connection) {
msg += colors.cyan(` (via ${context.connection.type} connection '${context.connection.name}')`);
}
return this.log('query', msg, context);
}
}