forked from Lilly-Protocol/lily-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstrumentation.ts
More file actions
73 lines (67 loc) · 2.06 KB
/
Copy pathinstrumentation.ts
File metadata and controls
73 lines (67 loc) · 2.06 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
72
73
/**
* Next.js Server Instrumentation
*
* This module is automatically loaded by Next.js at server startup.
* It provides hooks for observability, error tracking, and telemetry.
*
* @see https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation
*/
export async function register() {
// Only run on the Node.js runtime (not Edge)
if (process.env.NEXT_RUNTIME === "nodejs") {
console.log("[instrumentation] Server-side instrumentation registered");
// Hook into global error handling for structured logging
const originalConsoleError = console.error;
console.error = (...args: unknown[]) => {
const error = args[0];
const context = args[1] as Record<string, unknown> | undefined;
const structuredLog = {
timestamp: new Date().toISOString(),
level: "error",
message: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined,
route: context?.route ?? "unknown",
...(typeof context === "object" && context !== null ? context : {}),
};
originalConsoleError(JSON.stringify(structuredLog));
};
}
}
/**
* Called when a request-level error occurs during rendering or data fetching.
* Next.js 16+ invokes this hook automatically.
*/
export function onRequestError(
err: Error & { digest?: string },
request: {
path: string;
method: string;
headers?: Record<string, string>;
},
context: {
routerKind: string;
routePath: string;
routeType: string;
renderSource: string;
},
): void {
const logEntry = {
timestamp: new Date().toISOString(),
level: "error",
type: "request_error",
message: err.message,
digest: err.digest,
stack: err.stack,
request: {
path: request.path,
method: request.method,
},
context: {
routerKind: context.routerKind,
routePath: context.routePath,
routeType: context.routeType,
renderSource: context.renderSource,
},
};
console.error(JSON.stringify(logEntry));
}