-
Notifications
You must be signed in to change notification settings - Fork 283
/
Copy pathlog.ts
76 lines (63 loc) · 1.86 KB
/
log.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
import { CompiledQuery } from '../query-compiler/compiled-query.js'
import { freeze, isFunction } from './object-utils.js'
import { ArrayItemType } from './type-utils.js'
export const LOG_LEVELS = freeze(['query', 'error'] as const)
export type LogLevel = ArrayItemType<typeof LOG_LEVELS>
export interface QueryLogEvent {
readonly level: 'query'
readonly query: CompiledQuery
readonly queryDurationMillis: number
}
export interface ErrorLogEvent {
readonly level: 'error'
readonly error: unknown
}
export type LogEvent = QueryLogEvent | ErrorLogEvent
export type Logger = (event: LogEvent) => void
export type LogConfig = ReadonlyArray<LogLevel> | Logger
export class Log {
readonly #levels: Readonly<Record<LogLevel, boolean>>
readonly #logger: Logger
constructor(config: LogConfig) {
if (isFunction(config)) {
this.#logger = config
this.#levels = freeze({
query: true,
error: true,
})
} else {
this.#logger = defaultLogger
this.#levels = freeze({
query: config.includes('query'),
error: config.includes('error'),
})
}
}
isLevelEnabled(level: LogLevel): boolean {
return this.#levels[level]
}
query(getEvent: () => QueryLogEvent) {
if (this.#levels.query) {
this.#logger(getEvent())
}
}
error(getEvent: () => ErrorLogEvent) {
if (this.#levels.error) {
this.#logger(getEvent())
}
}
}
function defaultLogger(event: LogEvent): void {
if (event.level === 'query') {
console.log(`kysely:query: ${event.query.sql}`)
console.log(
`kysely:query: duration: ${event.queryDurationMillis.toFixed(1)}ms`
)
} else if (event.level === 'error') {
if (event.error instanceof Error) {
console.error(`kysely:error: ${event.error.stack ?? event.error.message}`)
} else {
console.error(`kysely:error: ${event}`)
}
}
}