forked from ZyntariHQ/Invoisio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracing.util.ts
More file actions
61 lines (53 loc) · 1.4 KB
/
Copy pathtracing.util.ts
File metadata and controls
61 lines (53 loc) · 1.4 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
import { randomUUID } from "node:crypto";
import { StructuredLogger } from "./structured-logger.service";
export type TraceCategory = "database" | "network";
export type TraceOptions = {
operation: string;
category: TraceCategory;
slowThresholdMs: number;
attributes?: Record<string, unknown>;
};
export async function traceAsync<T>(
logger: StructuredLogger,
options: TraceOptions,
fn: () => Promise<T>,
): Promise<T> {
const startedAt = Date.now();
const spanId = randomUUID();
logger.debug("span.start", {
spanId,
operation: options.operation,
category: options.category,
...options.attributes,
});
try {
const result = await fn();
const durationMs = Date.now() - startedAt;
const slow = durationMs >= options.slowThresholdMs;
const payload = {
spanId,
operation: options.operation,
category: options.category,
durationMs,
slow,
...options.attributes,
};
if (slow) {
logger.warn("span.slow", payload);
} else {
logger.debug("span.complete", payload);
}
return result;
} catch (error) {
const durationMs = Date.now() - startedAt;
logger.error("span.error", {
spanId,
operation: options.operation,
category: options.category,
durationMs,
error: error instanceof Error ? error.message : String(error),
...options.attributes,
});
throw error;
}
}