-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
memory.ts
93 lines (87 loc) · 2.64 KB
/
memory.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
import { required, unpartial } from 'type-plus'
import { toInspectLogEntry } from './platform.js'
import { formatLogLevel } from './formatter.js'
import type { LogEntry, LogFormatter, LogReporter, LogReporterOptions } from './types.js'
import { createConsoleLogReporter } from './console.js'
export type MemoryLogReporter = LogReporter<LogEntry> & {
logs: LogEntry[]
/**
* Gets a simple log message for testing.
* The message only contains arguments for each log entry.
*/
getLogMessage(): string
getLogMessages(): string[]
getLogMessageWithLevel(): string
getLogMessagesWithLevel(): string[]
getLogMessagesWithIdAndLevel(): string[]
emit(): void
}
export type MemoryLogFormatter = LogFormatter<LogEntry>
export function toMessageWithLevel(logs: LogEntry[]) {
return (
logs
.map(toInspectLogEntry)
.map(log => `${formatLogLevel(log.level)} ${log.args.join(' ')}`)
.join('\n')
// if it has more than this log,
// we assume it is running under tests,
// and remove this log to simplify testing.
.replace(/^\(WARN\) already configured for test, ignoring config\(\) call\n/, '')
)
}
export function createMemoryLogReporter(options?: LogReporterOptions<LogEntry>): MemoryLogReporter {
return Object.freeze(buildMemoryReporter(unpartial({ id: 'memory' }, options)))
}
function buildMemoryReporter(options?: LogReporterOptions<LogEntry>) {
const { id, formatter, filter } = required({ id: 'memory', formatter: (e: LogEntry) => e }, options)
const logs: LogEntry[] = []
return {
id,
get formatter() {
return formatter
},
get filter() {
return filter
},
logs,
write(entry: LogEntry) {
if (filter && !filter(entry)) return
logs.push(formatter(entry))
},
getLogMessage() {
return this.getLogMessages().join('\n')
},
getLogMessages() {
return logs.map(toInspectLogEntry).map(log => log.args.join(' '))
},
getLogMessagesWithLevel() {
return logs
.map(toInspectLogEntry)
.map(log => `${formatLogLevel(log.level)} ${log.args.join(' ')}`)
},
getLogMessagesWithIdAndLevel() {
return logs
.map(toInspectLogEntry)
.map(log => `${log.id} ${formatLogLevel(log.level)} ${log.args.join(' ')}`)
},
getLogMessageWithLevel() {
return toMessageWithLevel(logs)
},
/**
* emit the saved log to console for easy debugging
*/
emit() {
const reporter = createConsoleLogReporter()
logs.forEach(l => reporter.write(l))
}
}
}
export function createMemoryWithConsoleLogReporter(
options?: LogReporterOptions<LogEntry>
): MemoryLogReporter {
return Object.freeze(
Object.assign(buildMemoryReporter(unpartial({ id: 'memory-with-console' }, options)), {
isConsoleReporter: true
})
)
}