Skip to content

Commit 452a3ad

Browse files
committed
Add Sentry traceId to logs when available
1 parent 72599d9 commit 452a3ad

File tree

2 files changed

+38
-7
lines changed

2 files changed

+38
-7
lines changed

src/lib/shared/roarr/client.ts

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import type {
77
LoggerLoggingMethodName,
88
} from './types';
99
import { serializeError } from 'serialize-error';
10+
import { sentry } from '../sentry';
11+
import { getTraceId } from '../sentry/utils';
1012

1113
export const roarr = (function () {
1214
const createLogger = (methodName: LoggerLoggingMethodName) => {
@@ -15,11 +17,8 @@ export const roarr = (function () {
1517
return;
1618
}
1719

18-
const contextClone = { ...context } as LoggerContext;
19-
const errorContext = contextClone.error;
20-
if (errorContext && errorContext instanceof Error) {
21-
contextClone.error = serializeError(errorContext);
22-
}
20+
let contextClone = serializeErrorInContext(context);
21+
contextClone = enrichContextWithSentryTraceId(contextClone);
2322

2423
Roarr[methodName](
2524
config.roarr.isDebugContextShown
@@ -62,13 +61,43 @@ function shouldBeLogged(methodName: LoggerLoggingMethodName): boolean {
6261
return requestedLogLevel >= minLogLevel;
6362
}
6463

64+
function serializeErrorInContext(
65+
context: LoggerContextWithError,
66+
): LoggerContext {
67+
const errorContext = context.error;
68+
if (!errorContext || !(errorContext instanceof Error)) {
69+
return { ...context } as LoggerContext;
70+
}
71+
72+
return {
73+
...context,
74+
error: serializeError(errorContext),
75+
};
76+
}
77+
78+
function enrichContextWithSentryTraceId(context: LoggerContext): LoggerContext {
79+
if (!sentry) {
80+
return { ...context };
81+
}
82+
83+
const traceId = getTraceId();
84+
if (!traceId) {
85+
return { ...context };
86+
}
87+
88+
return {
89+
...context,
90+
sentryTraceId: traceId,
91+
};
92+
}
93+
6594
function enrichContextWithDebugInfo(
66-
override: LoggerContext = {},
95+
context: LoggerContext = {},
6796
): LoggerContext {
6897
return {
98+
...context,
6999
callName: getCallName(),
70100
fileName: getFileName(),
71-
...override,
72101
};
73102
}
74103

src/lib/shared/roarr/types/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,12 @@ export type JsonValue =
2424

2525
export interface LoggerContext extends JsonObject {
2626
error?: JsonValue;
27+
sentryTraceId?: string;
2728
}
2829

2930
export interface LoggerContextWithError {
3031
error?: Error | JsonValue;
32+
sentryTraceId?: string;
3133
// WARN: Other properties should not have an `Error` type, but I don't know
3234
// how to enforce it in combination with the type of `error` property.
3335
[k: string]: Error | JsonValue;

0 commit comments

Comments
 (0)