Add OpenTelemetry error handling in StartServer.ts

This commit is contained in:
Simon Larsen 2024-04-09 19:24:51 +01:00
parent e0bcfd31bf
commit 6ef91fd1b7
No known key found for this signature in database
GPG Key ID: AB45983AA9C81CDE
3 changed files with 64 additions and 2 deletions

View File

@ -118,6 +118,16 @@ app.use((req: ExpressRequest, res: ExpressResponse, next: NextFunction) => {
}
});
app.use((_req: ExpressRequest, _res: ExpressResponse, next: NextFunction) => {
// set span status code to OK by default. If the error occurs, it will be updated in the error handler.
const span: api.Span | undefined = api.trace.getSpan(api.context.active());
if (span) {
span.setStatus({ code: api.SpanStatusCode.OK });
}
next();
});
type InitFunction = (
appName: string,
port?: Port,
@ -188,10 +198,15 @@ const init: InitFunction = async (
logger.error(err);
// Mark span as error.
if (err) {
const span = api.trace.getSpan(api.context.active());
const span: api.Span | undefined = api.trace.getSpan(
api.context.active()
);
if (span) {
// record exception
span.recordException(err);
// set span status code to ERROR
span.setStatus({
code: api.SpanStatusCode.ERROR,
message: err.message,

View File

@ -19,6 +19,9 @@ import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'
import { Logger, logs } from '@opentelemetry/api-logs';
import { CompressionAlgorithm } from '@opentelemetry/otlp-exporter-base';
// Enable this line to see debug logs
// diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG);
export default class Telemetry {
public static sdk: opentelemetry.NodeSDK | null = null;
public static logger: Logger | null = null;

View File

@ -150,6 +150,50 @@ router.post(
dbSpan.endTimeUnixNano = span[
'endTimeUnixNano'
] as number;
let spanStatusCode: number = 0;
if (
span['status'] &&
(span['status'] as JSONObject)?.['code'] &&
typeof (span['status'] as JSONObject)?.['code'] ===
'number'
) {
spanStatusCode = (span['status'] as JSONObject)?.[
'code'
] as number;
}
if (
span['status'] &&
(span['status'] as JSONObject)?.['code'] &&
typeof (span['status'] as JSONObject)?.['code'] ===
'string'
) {
if (
(span['status'] as JSONObject)?.['code'] ===
'STATUS_CODE_UNSET'
) {
spanStatusCode = 0;
} else if (
(span['status'] as JSONObject)?.['code'] ===
'STATUS_CODE_OK'
) {
spanStatusCode = 1;
} else if (
(span['status'] as JSONObject)?.['code'] ===
'STATUS_CODE_ERROR'
) {
spanStatusCode = 2;
}
}
dbSpan.statusCode = spanStatusCode;
dbSpan.statusMessage = (span['status'] as JSONObject)?.[
'message'
] as string;
dbSpan.startTime = OneUptimeDate.fromUnixNano(
span['startTimeUnixNano'] as number
);