Skip to content
This repository was archived by the owner on Mar 18, 2025. It is now read-only.

Commit 6b9c710

Browse files
authored
feat(instrumentation): add shutdown hook (#142)
Signed-off-by: Tomas Dvorak <toomas2d@gmail.com>
1 parent 9e6a2e0 commit 6b9c710

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

src/opentelemetry.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616

1717
import 'dotenv/config';
1818

19+
import { setTimeout } from 'node:timers/promises';
20+
1921
import { NodeSDK, resources, metrics } from '@opentelemetry/sdk-node';
2022
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
2123
import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
@@ -33,3 +35,21 @@ export const opentelemetrySDK = new NodeSDK({
3335
instrumentations: [...getNodeAutoInstrumentations()]
3436
});
3537
opentelemetrySDK.start();
38+
39+
let isShuttingDown = false;
40+
const { promise, resolve } = Promise.withResolvers<void>();
41+
42+
for (const event of ['beforeExit', 'SIGINT', 'SIGTERM']) {
43+
process.once(event, () => {
44+
if (!isShuttingDown) {
45+
isShuttingDown = true;
46+
Promise.race([opentelemetrySDK.shutdown(), setTimeout(5_000, null, { ref: false })])
47+
.catch((err) => {
48+
// eslint-disable-next-line no-console
49+
console.error(`Failed to execute shutdown hook`, err);
50+
})
51+
.finally(() => resolve());
52+
}
53+
return promise;
54+
});
55+
}

0 commit comments

Comments
 (0)