@devopsplaybook.io/otel-utils-fastify 0.0.1-beta1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 devopsplaybook.io
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # otel-utils-fastify
package/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ // Entry point for the otel-utils npm package
2
+ // Export all modules from src
3
+
4
+ export * from "./src/Logger";
5
+ export * from "./src/StandardMeter";
6
+ export * from "./src/StandardTracer";
7
+ export * from "./src/models/ConfigInterfaceOTel";
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@devopsplaybook.io/otel-utils-fastify",
3
+ "version": "0.0.1-beta1",
4
+ "description": "Utility to simplify integration with Open Telemetry for Fastify API Server",
5
+ "keywords": [
6
+ "Open",
7
+ "Telemetry",
8
+ "Traces",
9
+ "Logs",
10
+ "Metrics"
11
+ ],
12
+ "license": "ISC",
13
+ "author": "",
14
+ "type": "commonjs",
15
+ "main": "dist/index.js",
16
+ "types": "dist/index.d.ts",
17
+ "scripts": {
18
+ "build": "tsc",
19
+ "test": "echo \"Error: no test specified\" && exit 1"
20
+ },
21
+ "dependencies": {
22
+ "fastify": "^5.5.0",
23
+ "@devopsplaybook.io/otel-utils": "1.0.1-beta3"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "^24.3.0",
27
+ "@types/sqlite3": "^5.1.0"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ }
32
+ }
package/src/Logger.ts ADDED
@@ -0,0 +1,120 @@
1
+ import type { Logger as OTelLogger } from "@opentelemetry/api-logs";
2
+ import { SeverityNumber } from "@opentelemetry/api-logs";
3
+ import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
4
+ import { resourceFromAttributes } from "@opentelemetry/resources";
5
+ import {
6
+ BatchLogRecordProcessor,
7
+ LoggerProvider,
8
+ } from "@opentelemetry/sdk-logs";
9
+ import { Span } from "@opentelemetry/sdk-trace-base";
10
+ import {
11
+ ATTR_NETWORK_LOCAL_ADDRESS,
12
+ ATTR_SERVICE_NAME,
13
+ ATTR_SERVICE_VERSION,
14
+ } from "@opentelemetry/semantic-conventions";
15
+ import * as os from "os";
16
+ import { ConfigInterfaceOTel } from "./models/ConfigInterfaceOTel";
17
+ import { StandardTracerStartSpan } from "./StandardTracer";
18
+
19
+ let loggerOTel: OTelLogger;
20
+
21
+ export function LoggerInit(context: Span, config: ConfigInterfaceOTel) {
22
+ const span = StandardTracerStartSpan("LoggerInit", context);
23
+
24
+ if (config.OPENTELEMETRY_COLLECTOR_HTTP_LOGS) {
25
+ const exporterHeaders: Record<string, string> = {};
26
+ if (config.OPENTELEMETRY_COLLECT_AUTHORIZATION_HEADER) {
27
+ exporterHeaders[
28
+ "Authorization"
29
+ ] = `Bearer ${config.OPENTELEMETRY_COLLECT_AUTHORIZATION_HEADER}`;
30
+ }
31
+ const exporter = new OTLPLogExporter({
32
+ url: config.OPENTELEMETRY_COLLECTOR_HTTP_LOGS,
33
+ headers: exporterHeaders,
34
+ });
35
+
36
+ const loggerProvider = new LoggerProvider({
37
+ processors: [
38
+ new BatchLogRecordProcessor(exporter, {
39
+ maxQueueSize: 100,
40
+ scheduledDelayMillis:
41
+ config.OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_INTERVAL_SECONDS * 1000,
42
+ }),
43
+ ],
44
+ resource: resourceFromAttributes({
45
+ [ATTR_SERVICE_NAME]: `${config.SERVICE_ID}`,
46
+ [ATTR_SERVICE_VERSION]: `${config.VERSION}`,
47
+ [ATTR_NETWORK_LOCAL_ADDRESS]: os.hostname(),
48
+ }),
49
+ });
50
+
51
+ loggerOTel = loggerProvider.getLogger(
52
+ `${config.SERVICE_ID}:${config.VERSION}`
53
+ );
54
+ }
55
+ span.end();
56
+ }
57
+
58
+ const DEV_MODE = (() => {
59
+ if (process.env.NODE_ENV === "dev") {
60
+ return true;
61
+ }
62
+ return false;
63
+ })();
64
+
65
+ export class Logger {
66
+ private module: string;
67
+
68
+ constructor(module: string) {
69
+ this.module = `${module}`;
70
+ }
71
+
72
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
73
+ public debug(message: Error | string | any): void {
74
+ if (DEV_MODE) {
75
+ this.display("debug", message, SeverityNumber.DEBUG);
76
+ }
77
+ }
78
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
79
+ public info(message: Error | string | any): void {
80
+ this.display("info", message, SeverityNumber.WARN);
81
+ }
82
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
83
+ public warn(message: Error | string | any): void {
84
+ this.display("warn", message, SeverityNumber.WARN);
85
+ }
86
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
87
+ public error(message: Error | string | any): void {
88
+ this.display("error", message, SeverityNumber.ERROR);
89
+ }
90
+
91
+ private display(
92
+ level: string,
93
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
94
+ message: any,
95
+ severityNumber = SeverityNumber.INFO
96
+ ): void {
97
+ if (typeof message === "string") {
98
+ // eslint:disable-next-line:no-console
99
+ console.log(`[${level}] [${this.module}] ${message}`);
100
+ } else if (message instanceof Error) {
101
+ // eslint:disable-next-line:no-console
102
+ console.log(`${level} [${this.module}] ${message}`);
103
+ // eslint:disable-next-line:no-console
104
+ console.log((message as Error).stack);
105
+ } else if (typeof message === "object") {
106
+ // eslint:disable-next-line:no-console
107
+ console.log(`${level} [${this.module}] ${JSON.stringify(message)}`);
108
+ }
109
+ if (loggerOTel) {
110
+ {
111
+ loggerOTel.emit({
112
+ severityNumber,
113
+ severityText: level,
114
+ body: message,
115
+ attributes: { "log.type": "custom" },
116
+ });
117
+ }
118
+ }
119
+ }
120
+ }
@@ -0,0 +1,91 @@
1
+ import { Counter, Histogram, ObservableGauge } from "@opentelemetry/api";
2
+ import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
3
+ import { resourceFromAttributes } from "@opentelemetry/resources";
4
+ import {
5
+ MeterProvider,
6
+ PeriodicExportingMetricReader,
7
+ } from "@opentelemetry/sdk-metrics";
8
+ import {
9
+ ATTR_NETWORK_LOCAL_ADDRESS,
10
+ ATTR_SERVICE_NAME,
11
+ ATTR_SERVICE_VERSION,
12
+ } from "@opentelemetry/semantic-conventions";
13
+ import * as os from "os";
14
+ import { ConfigInterfaceOTel } from "./models/ConfigInterfaceOTel";
15
+
16
+ let meterProvider: MeterProvider;
17
+ let config: ConfigInterfaceOTel;
18
+ const METER_NAME = "default";
19
+
20
+ //
21
+ export function StandardMeterInitTelemetry(initConfig: ConfigInterfaceOTel) {
22
+ config = initConfig;
23
+
24
+ // Metrics
25
+ if (config.OPENTELEMETRY_COLLECTOR_HTTP_METRICS) {
26
+ const collectorOptions = {
27
+ url: config.OPENTELEMETRY_COLLECTOR_HTTP_METRICS,
28
+ headers: {} as Record<string, string>,
29
+ concurrencyLimit: 1,
30
+ };
31
+ if (config.OPENTELEMETRY_COLLECT_AUTHORIZATION_HEADER) {
32
+ collectorOptions.headers[
33
+ "Authorization"
34
+ ] = `Bearer ${config.OPENTELEMETRY_COLLECT_AUTHORIZATION_HEADER}`;
35
+ }
36
+ const metricExporter = new OTLPMetricExporter(collectorOptions);
37
+ meterProvider = new MeterProvider({
38
+ resource: resourceFromAttributes({
39
+ [ATTR_SERVICE_NAME]: `${config.SERVICE_ID}`,
40
+ [ATTR_SERVICE_VERSION]: `${config.VERSION}`,
41
+ [ATTR_NETWORK_LOCAL_ADDRESS]: os.hostname(),
42
+ }),
43
+ readers: [
44
+ new PeriodicExportingMetricReader({
45
+ exporter: metricExporter,
46
+ exportIntervalMillis:
47
+ config.OPENTELEMETRY_COLLECTOR_EXPORT_METRICS_INTERVAL_SECONDS *
48
+ 1000,
49
+ }),
50
+ ],
51
+ });
52
+ } else {
53
+ meterProvider = new MeterProvider({
54
+ resource: resourceFromAttributes({
55
+ [ATTR_SERVICE_NAME]: `${config.SERVICE_ID}`,
56
+ [ATTR_SERVICE_VERSION]: `${config.VERSION}`,
57
+ [ATTR_NETWORK_LOCAL_ADDRESS]: os.hostname(),
58
+ }),
59
+ });
60
+ }
61
+ }
62
+
63
+ export function StandardMeterCreateCounter(key: string): Counter {
64
+ const meter = meterProvider.getMeter(METER_NAME);
65
+ return meter.createCounter(`${config.SERVICE_ID}.${key}`);
66
+ }
67
+
68
+ export function StandardMeterCreateUpDownCounter(key: string): Counter {
69
+ const meter = meterProvider.getMeter(METER_NAME);
70
+ return meter.createUpDownCounter(`${config.SERVICE_ID}.${key}`);
71
+ }
72
+
73
+ export function StandardMeterCreateHistorgram(key: string): Histogram {
74
+ const meter = meterProvider.getMeter(METER_NAME);
75
+ return meter.createHistogram(`${config.SERVICE_ID}.${key}`);
76
+ }
77
+
78
+ export function StandardMeterCreateObservableGauge(
79
+ key: string,
80
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
81
+ callback: (observableResult: any) => void,
82
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
83
+ description: any = null
84
+ ): ObservableGauge {
85
+ const meter = meterProvider.getMeter(METER_NAME);
86
+ const observableGauge = meter.createObservableGauge(key, description);
87
+
88
+ observableGauge.addCallback(callback);
89
+
90
+ return observableGauge;
91
+ }
@@ -0,0 +1,105 @@
1
+ import opentelemetry, {
2
+ defaultTextMapSetter,
3
+ ROOT_CONTEXT,
4
+ trace,
5
+ Tracer,
6
+ } from "@opentelemetry/api";
7
+ import { AsyncHooksContextManager } from "@opentelemetry/context-async-hooks";
8
+ import { W3CTraceContextPropagator } from "@opentelemetry/core";
9
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
10
+ import { AWSXRayIdGenerator } from "@opentelemetry/id-generator-aws-xray";
11
+ import { resourceFromAttributes } from "@opentelemetry/resources";
12
+ import { BatchSpanProcessor, Span } from "@opentelemetry/sdk-trace-base";
13
+ import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
14
+ import {
15
+ ATTR_HTTP_REQUEST_METHOD,
16
+ ATTR_HTTP_ROUTE,
17
+ ATTR_NETWORK_LOCAL_ADDRESS,
18
+ ATTR_SERVICE_NAME,
19
+ ATTR_SERVICE_VERSION,
20
+ } from "@opentelemetry/semantic-conventions";
21
+ import * as os from "os";
22
+ import { ConfigInterfaceOTel } from "./models/ConfigInterfaceOTel";
23
+
24
+ let tracerInstance: Tracer;
25
+ const propagator = new W3CTraceContextPropagator();
26
+ let config: ConfigInterfaceOTel;
27
+
28
+ //
29
+ export function StandardTracerInitTelemetry(initConfig: ConfigInterfaceOTel) {
30
+ config = initConfig;
31
+ const spanProcessors = [];
32
+
33
+ if (config.OPENTELEMETRY_COLLECTOR_HTTP_TRACES) {
34
+ const exporterHeaders: Record<string, string> = {};
35
+ if (config.OPENTELEMETRY_COLLECT_AUTHORIZATION_HEADER) {
36
+ exporterHeaders[
37
+ "Authorization"
38
+ ] = `Bearer ${config.OPENTELEMETRY_COLLECT_AUTHORIZATION_HEADER}`;
39
+ }
40
+ const exporter = new OTLPTraceExporter({
41
+ url: config.OPENTELEMETRY_COLLECTOR_HTTP_TRACES,
42
+ headers: exporterHeaders,
43
+ });
44
+ spanProcessors.push(new BatchSpanProcessor(exporter));
45
+ }
46
+ const traceProvider = new NodeTracerProvider({
47
+ idGenerator: new AWSXRayIdGenerator(),
48
+ resource: resourceFromAttributes({
49
+ [ATTR_SERVICE_NAME]: `${config.SERVICE_ID}`,
50
+ [ATTR_SERVICE_VERSION]: `${config.VERSION}`,
51
+ [ATTR_NETWORK_LOCAL_ADDRESS]: os.hostname(),
52
+ }),
53
+ spanProcessors,
54
+ });
55
+ traceProvider.register();
56
+ const contextManager = new AsyncHooksContextManager();
57
+ contextManager.enable();
58
+ opentelemetry.context.setGlobalContextManager(contextManager);
59
+ }
60
+
61
+ export function StandardTracerStartSpan(name: string, parentSpan?: Span): Span {
62
+ const sanitizedName = String(name).replace(/[^a-zA-Z0-9-_/]/g, "_");
63
+ const tracer = StandardTracerGetTracer();
64
+
65
+ if (parentSpan) {
66
+ return tracer.startSpan(
67
+ sanitizedName,
68
+ undefined,
69
+ opentelemetry.trace.setSpan(opentelemetry.context.active(), parentSpan)
70
+ ) as Span;
71
+ }
72
+
73
+ const span = tracer.startSpan(sanitizedName) as Span;
74
+
75
+ span.setAttribute(ATTR_HTTP_REQUEST_METHOD, `BACKEND`);
76
+ span.setAttribute(
77
+ ATTR_HTTP_ROUTE,
78
+ `${config.SERVICE_ID}-${config.VERSION}-${sanitizedName}`
79
+ );
80
+ return span;
81
+ }
82
+
83
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
84
+ export function StandardTracerGetTracer(): any {
85
+ if (!tracerInstance) {
86
+ tracerInstance = opentelemetry.trace.getTracer(
87
+ `${config.SERVICE_ID}:${config.VERSION}`
88
+ );
89
+ }
90
+ return tracerInstance;
91
+ }
92
+
93
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
94
+ export function StandardTracerAppendHeader(context: Span, headers = {}): any {
95
+ if (!headers) {
96
+ headers = {};
97
+ }
98
+ propagator.inject(
99
+ trace.setSpanContext(ROOT_CONTEXT, context.spanContext()),
100
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
101
+ headers as any,
102
+ defaultTextMapSetter
103
+ );
104
+ return headers;
105
+ }
@@ -0,0 +1,11 @@
1
+ export interface ConfigInterfaceOTel {
2
+ SERVICE_ID: string;
3
+ VERSION: number;
4
+ OPENTELEMETRY_COLLECTOR_HTTP_TRACES: string;
5
+ OPENTELEMETRY_COLLECTOR_HTTP_METRICS: string;
6
+ OPENTELEMETRY_COLLECTOR_HTTP_LOGS: string;
7
+ OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_INTERVAL_SECONDS: number;
8
+ OPENTELEMETRY_COLLECTOR_EXPORT_METRICS_INTERVAL_SECONDS: number;
9
+ OPENTELEMETRY_COLLECTOR_AWS: boolean;
10
+ OPENTELEMETRY_COLLECT_AUTHORIZATION_HEADER: string;
11
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2019",
4
+ "module": "commonjs",
5
+ "declaration": true,
6
+ "outDir": "./dist",
7
+ "strict": true,
8
+ "esModuleInterop": true,
9
+ "skipLibCheck": true,
10
+ "forceConsistentCasingInFileNames": true
11
+ },
12
+ "include": ["index.ts", "src/**/*"]
13
+ }