Repository navigation
Expand file tree
/
Copy pathpatchConsole.ts
More file actions
71 lines (56 loc) · 1.97 KB
/
Copy pathpatchConsole.ts
File metadata and controls
71 lines (56 loc) · 1.97 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
70
71
import { format } from 'node:util';
import { SharedContext } from './SharedContext.ts';
/**
Stores the original console methods so they can be restored by `unpatchConsole()`.
*/
const originals = {
log: console.log,
info: console.info,
warn: console.warn,
error: console.error,
debug: console.debug,
};
let patched = false;
/**
Monkey-patches `console.log`, `console.info`, `console.warn`, `console.error`, and `console.debug` so that their output flows through the effective IOContext's stdout/stderr streams.
This makes all console output compatible with TeeStream (logging to file) and any other IOContext-based output capture.
Before `OpRunner.create()` is called, `SharedContext.effectiveIOContext` falls back to `process.stdout`/`process.stderr`, so the patch is effectively a no-op until the framework is initialized.
This function is idempotent — calling it multiple times is safe.
// TODO: In a future PR, console.debug could be routed to file-only logging
// TODO: Consider patching console.table, console.group, console.time, etc.
*/
export function patchConsole(): void
{
if (patched) return;
patched = true;
console.log = (...args: unknown[]): void =>
{
SharedContext.effectiveIOContext.stdout.write(format(...args) + '\n');
};
console.info = console.log;
console.warn = (...args: unknown[]): void =>
{
SharedContext.effectiveIOContext.stderr.write(format(...args) + '\n');
};
console.error = console.warn;
// TODO: console.debug could route to file-only logging in a future PR.
// For now, it behaves the same as console.log.
console.debug = console.log;
}
/**
Restores the original console methods, undoing the monkey-patch.
Mainly useful in tests to ensure a clean environment.
*/
export function unpatchConsole(): void
{
if (!patched) return;
Object.assign(console, originals);
patched = false;
}
/**
Returns whether the console is currently patched.
*/
export function isConsolePatched(): boolean
{
return patched;
}