Skip to content

Commit 3e9e403

Browse files
committed
Adds disposable logger
- Similar to the log decorator, but usable in a function with `using`
1 parent d3f8222 commit 3e9e403

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

src/system/loggable.ts

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { hrtime } from '@env/hrtime';
2+
import { Logger } from './logger';
3+
import type { LogScope } from './logger.scope';
4+
import { setLogScopeExit, startLogScope } from './logger.scope';
5+
import { getDurationMilliseconds } from './string';
6+
7+
export class LoggableScope implements Disposable {
8+
private readonly scope: LogScope & Disposable;
9+
private readonly start: [number, number];
10+
11+
constructor(
12+
prefix: string,
13+
private readonly options?: { debug?: boolean; enter?: string },
14+
) {
15+
this.scope = startLogScope(prefix, true);
16+
this.start = hrtime();
17+
18+
(options?.debug ? Logger.debug : Logger.log).call(Logger, this.scope, options?.enter ?? '');
19+
}
20+
21+
[Symbol.dispose](): void {
22+
const duration = getDurationMilliseconds(this.start);
23+
const timing = ` [${duration}ms]`;
24+
const exit = this.scope.exitFailed ?? 'completed';
25+
26+
if (this.scope.exitFailed != null) {
27+
Logger.error(null, this.scope, `${exit}${this.scope.exitDetails ?? ''}${timing}`);
28+
} else {
29+
(this.options?.debug ? Logger.debug : Logger.log).call(
30+
Logger,
31+
this.scope,
32+
`${exit}${this.scope.exitDetails ?? ''}${timing}`,
33+
);
34+
}
35+
36+
this.scope[Symbol.dispose]();
37+
}
38+
39+
setExit(details: string | undefined, failed?: string): void {
40+
setLogScopeExit(this.scope, details, failed);
41+
}
42+
43+
error(ex: Error | unknown, message?: string, ...params: any[]): void {
44+
Logger.error(ex, this.scope, message, ...params);
45+
}
46+
47+
log(message: string, ...params: any[]): void {
48+
(this.options?.debug ? Logger.debug : Logger.log).call(Logger, this.scope, message, ...params);
49+
}
50+
51+
warn(message: string, ...params: any[]): void {
52+
Logger.warn(this.scope, message, ...params);
53+
}
54+
}
55+
56+
export function maybeStartLoggableScope(prefix: string, options?: { debug?: boolean; enter?: string }) {
57+
return Logger.enabled('error') ? new LoggableScope(prefix, options) : undefined;
58+
}

0 commit comments

Comments
 (0)