-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinstrumentation.ts
More file actions
84 lines (77 loc) · 3.03 KB
/
Copy pathinstrumentation.ts
File metadata and controls
84 lines (77 loc) · 3.03 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
74
75
76
77
78
79
80
81
82
83
84
/**
* Next.js Instrumentation Hook
*
* This file is automatically loaded by Next.js on both server and edge runtimes.
* It initializes New Relic APM for server-side monitoring.
*
* Documentation: https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation
*/
const instrumentationLogger = {
error(message: string, attributes?: Record<string, unknown>) {
const payload = attributes
? `${message} ${JSON.stringify(attributes)}`
: `${message}`;
const error = new Error(payload);
if (typeof globalThis.reportError === "function") {
globalThis.reportError(error);
return;
}
console.error(error);
},
};
export async function register() {
// Only initialize New Relic on the Node.js runtime (not Edge runtime)
if (process.env.NEXT_RUNTIME === "nodejs") {
try {
const { registerPostHogProcessHandlers } = await import(
"./src/lib/posthog-server"
);
registerPostHogProcessHandlers();
} catch (error) {
// PostHog runtime hooks are optional and should not block startup.
instrumentationLogger.error(
"[PostHog] Failed to register process handlers",
{
error:
error instanceof Error
? {
message: error.message,
name: error.name,
stack: error.stack,
}
: String(error),
},
);
}
const newrelicLicenseKey = process.env.NEW_RELIC_LICENSE_KEY;
const newrelicAppName = process.env.NEW_RELIC_APP_NAME;
// Only initialize if both license key and app name are provided
if (newrelicLicenseKey && newrelicAppName) {
try {
// Dynamic import to avoid loading New Relic on Edge runtime
// New Relic will automatically load the newrelic.cjs config file
const newrelic = await import("newrelic");
// Return the newrelic instance for potential use
return newrelic;
} catch (error) {
// If New Relic fails to initialize, log the error but don't crash the app
console.error(
"[New Relic] Failed to initialize:",
error instanceof Error ? error.message : String(error),
);
}
} else {
// If credentials are missing, log a warning but don't fail
if (!newrelicLicenseKey) {
console.warn(
"[New Relic] NEW_RELIC_LICENSE_KEY not found - APM monitoring disabled",
);
}
if (!newrelicAppName) {
console.warn(
"[New Relic] NEW_RELIC_APP_NAME not found - APM monitoring disabled",
);
}
}
}
}