Repository navigation
Expand file tree
/
Copy pathlog.ts
More file actions
69 lines (58 loc) · 1.77 KB
/
Copy pathlog.ts
File metadata and controls
69 lines (58 loc) · 1.77 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
import type internal from "node:stream";
import { Writable } from "node:stream";
export const createLogger = (context: string) => {
context = context.toUpperCase();
const doLog = (level: LogLevel, ...args: unknown[]): string | void => {
if (options.level > level) return;
levelConsoleMap[level](
`[${context}${options.include_date ? ` ${new Date().toISOString()}` : ""}]`,
...args,
);
return args.join(" ");
};
return {
error: (...args: unknown[]) => doLog(LogLevel.error, ...args),
warn: (...args: unknown[]) => doLog(LogLevel.warn, ...args),
msg: (...args: unknown[]) => doLog(LogLevel.msg, ...args),
verbose: (...args: unknown[]) => doLog(LogLevel.verbose, ...args),
};
};
class LogStream extends Writable {
private logger;
constructor(context: string, opts?: internal.WritableOptions) {
super(opts);
this.logger = createLogger(context);
}
_write(
chunk: unknown,
_encoding: BufferEncoding,
callback: (error?: Error | null) => void,
): void {
this.logger.msg(String(chunk).trimEnd());
callback();
}
}
export const createLogStream = (context: string) => new LogStream(context);
export enum LogLevel {
verbose = 0,
msg = 1,
warn = 2,
error = 3,
none = 4,
}
const levelConsoleMap = {
[LogLevel.verbose]: console.log,
[LogLevel.msg]: console.log,
[LogLevel.warn]: console.warn,
[LogLevel.error]: console.error,
[LogLevel.none]: () => {},
} satisfies Record<LogLevel, (...data: unknown[]) => void>;
// we can't use config here because importing config ends up parsing it
// bit of an oversight... but we can work around that by exposing a setter
const options = {
level: process.env.VITEST ? LogLevel.none : LogLevel.verbose,
include_date: true,
};
export const setLogOptions = (opts: typeof options) => {
Object.assign(options, opts);
};