Skip to content

Commit

Permalink
feat(instrumentation): add shutdown hook (#142)
Browse files Browse the repository at this point in the history
Signed-off-by: Tomas Dvorak <[email protected]>
  • Loading branch information
Tomas2D authored Jan 6, 2025
1 parent 9e6a2e0 commit 6b9c710
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/opentelemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

import 'dotenv/config';

import { setTimeout } from 'node:timers/promises';

import { NodeSDK, resources, metrics } from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
Expand All @@ -33,3 +35,21 @@ export const opentelemetrySDK = new NodeSDK({
instrumentations: [...getNodeAutoInstrumentations()]
});
opentelemetrySDK.start();

let isShuttingDown = false;
const { promise, resolve } = Promise.withResolvers<void>();

for (const event of ['beforeExit', 'SIGINT', 'SIGTERM']) {
process.once(event, () => {
if (!isShuttingDown) {
isShuttingDown = true;
Promise.race([opentelemetrySDK.shutdown(), setTimeout(5_000, null, { ref: false })])
.catch((err) => {
// eslint-disable-next-line no-console
console.error(`Failed to execute shutdown hook`, err);
})
.finally(() => resolve());
}
return promise;
});
}

0 comments on commit 6b9c710

Please sign in to comment.