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

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.
@@ -0,0 +1 @@
1
+ export * from "./src/StandardTracerFastify";
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ // Entry point for the otel-utils npm package
3
+ // Export all modules from src
4
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
+ if (k2 === undefined) k2 = k;
6
+ var desc = Object.getOwnPropertyDescriptor(m, k);
7
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8
+ desc = { enumerable: true, get: function() { return m[k]; } };
9
+ }
10
+ Object.defineProperty(o, k2, desc);
11
+ }) : (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ o[k2] = m[k];
14
+ }));
15
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
17
+ };
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ __exportStar(require("./src/StandardTracerFastify"), exports);
@@ -0,0 +1,4 @@
1
+ import { ConfigInterfaceOTel } from "@devopsplaybook.io/otel-utils";
2
+ import { FastifyInstance } from "fastify";
3
+ export declare function StandardTracerFastifyRegisterHooks(fastify: FastifyInstance, config: ConfigInterfaceOTel): Promise<void>;
4
+ export declare function StandardTracerFastifyInit(fastify: FastifyInstance): void;
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StandardTracerFastifyRegisterHooks = StandardTracerFastifyRegisterHooks;
4
+ exports.StandardTracerFastifyInit = StandardTracerFastifyInit;
5
+ const otel_utils_1 = require("@devopsplaybook.io/otel-utils");
6
+ const api_1 = require("@opentelemetry/api");
7
+ const core_1 = require("@opentelemetry/core");
8
+ const sdk_node_1 = require("@opentelemetry/sdk-node");
9
+ const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
10
+ const propagator = new core_1.W3CTraceContextPropagator();
11
+ const logger = new otel_utils_1.Logger("StandardTracerFastify");
12
+ async function StandardTracerFastifyRegisterHooks(fastify, config) {
13
+ fastify.addHook("onRequest", async (req) => {
14
+ if (req.url.indexOf("/api") !== 0) {
15
+ return;
16
+ }
17
+ let spanName = `${req.method}-${req.url}`;
18
+ let urlName = req.url;
19
+ if (config.OPENTELEMETRY_COLLECTOR_AWS) {
20
+ spanName = `${config.SERVICE_ID}-${config.VERSION}`;
21
+ urlName = `${config.SERVICE_ID}-${config.VERSION}-${req.method}-${req.url}`;
22
+ }
23
+ const callerContext = propagator.extract(api_1.ROOT_CONTEXT, req.headers, api_1.defaultTextMapGetter);
24
+ sdk_node_1.api.context.with(callerContext, () => {
25
+ const span = (0, otel_utils_1.StandardTracerStartSpan)(spanName);
26
+ span.setAttribute(semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD, req.method);
27
+ span.setAttribute(semantic_conventions_1.ATTR_URL_PATH, urlName);
28
+ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
29
+ req.tracerSpanApi = span;
30
+ });
31
+ });
32
+ fastify.addHook("onResponse", async (req, reply) => {
33
+ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
34
+ const span = req.tracerSpanApi;
35
+ if (reply.statusCode > 299) {
36
+ span.status.code = api_1.SpanStatusCode.ERROR;
37
+ }
38
+ else {
39
+ span.status.code = api_1.SpanStatusCode.OK;
40
+ }
41
+ span.setAttribute(semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE, reply.statusCode);
42
+ span.end();
43
+ });
44
+ fastify.addHook("onError", async (req, reply, error) => {
45
+ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
46
+ const span = req.tracerSpanApi;
47
+ span.status.code = api_1.SpanStatusCode.ERROR;
48
+ span.recordException(error);
49
+ logger.error(error);
50
+ });
51
+ }
52
+ function StandardTracerFastifyInit(fastify) {
53
+ fastify.addHook("onRequest", async (req) => {
54
+ const spanName = `${req.method}-${req.url}`;
55
+ const urlName = req.url;
56
+ const callerContext = propagator.extract(api_1.ROOT_CONTEXT, req.headers, api_1.defaultTextMapGetter);
57
+ sdk_node_1.api.context.with(callerContext, () => {
58
+ const span = (0, otel_utils_1.StandardTracerStartSpan)(spanName);
59
+ span.setAttribute(semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD, req.method);
60
+ span.setAttribute(semantic_conventions_1.ATTR_URL_PATH, urlName);
61
+ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
62
+ req.tracerSpanApi = span;
63
+ });
64
+ });
65
+ fastify.addHook("onResponse", async (req, reply) => {
66
+ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
67
+ const span = req.tracerSpanApi;
68
+ if (reply.statusCode > 299) {
69
+ span.status.code = api_1.SpanStatusCode.ERROR;
70
+ }
71
+ else {
72
+ span.status.code = api_1.SpanStatusCode.OK;
73
+ }
74
+ span.setAttribute(semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE, reply.statusCode);
75
+ span.end();
76
+ });
77
+ fastify.addHook("onError", async (req, reply, error) => {
78
+ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
79
+ const span = req.tracerSpanApi;
80
+ span.status.code = api_1.SpanStatusCode.ERROR;
81
+ span.recordException(error);
82
+ });
83
+ }
@@ -0,0 +1,10 @@
1
+ // @ts-check
2
+
3
+ import eslint from "@eslint/js";
4
+ import tseslint from "typescript-eslint";
5
+
6
+ export default tseslint.config(
7
+ eslint.configs.recommended,
8
+ ...tseslint.configs.strict,
9
+ ...tseslint.configs.stylistic
10
+ );
package/index.ts CHANGED
@@ -1,7 +1,4 @@
1
1
  // Entry point for the otel-utils npm package
2
2
  // Export all modules from src
3
3
 
4
- export * from "./src/Logger";
5
- export * from "./src/StandardMeter";
6
- export * from "./src/StandardTracer";
7
- export * from "./src/models/ConfigInterfaceOTel";
4
+ export * from "./src/StandardTracerFastify";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devopsplaybook.io/otel-utils-fastify",
3
- "version": "0.0.1-beta1",
3
+ "version": "0.0.1-beta2",
4
4
  "description": "Utility to simplify integration with Open Telemetry for Fastify API Server",
5
5
  "keywords": [
6
6
  "Open",
@@ -20,11 +20,15 @@
20
20
  },
21
21
  "dependencies": {
22
22
  "fastify": "^5.5.0",
23
- "@devopsplaybook.io/otel-utils": "1.0.1-beta3"
23
+ "@devopsplaybook.io/otel-utils": "1.0.1-beta4"
24
24
  },
25
25
  "devDependencies": {
26
+ "@eslint/js": "^9.34.0",
26
27
  "@types/node": "^24.3.0",
27
- "@types/sqlite3": "^5.1.0"
28
+ "@types/sqlite3": "^5.1.0",
29
+ "ts-node": "^10.9.2",
30
+ "typescript-eslint": "^8.40.0",
31
+ "typescript": "^5.9.2"
28
32
  },
29
33
  "publishConfig": {
30
34
  "access": "public"
@@ -0,0 +1,5 @@
1
+ {
2
+ "tabWidth": 2,
3
+ "semi": true,
4
+ "singleQuote": false
5
+ }
@@ -0,0 +1,110 @@
1
+ import {
2
+ ConfigInterfaceOTel,
3
+ Logger,
4
+ StandardTracerStartSpan,
5
+ } from "@devopsplaybook.io/otel-utils";
6
+ import {
7
+ defaultTextMapGetter,
8
+ ROOT_CONTEXT,
9
+ SpanStatusCode,
10
+ } from "@opentelemetry/api";
11
+ import { W3CTraceContextPropagator } from "@opentelemetry/core";
12
+ import { api } from "@opentelemetry/sdk-node";
13
+ import { Span } from "@opentelemetry/sdk-trace-base";
14
+ import {
15
+ ATTR_HTTP_REQUEST_METHOD,
16
+ ATTR_HTTP_RESPONSE_STATUS_CODE,
17
+ ATTR_URL_PATH,
18
+ } from "@opentelemetry/semantic-conventions";
19
+ import { FastifyInstance } from "fastify";
20
+
21
+ const propagator = new W3CTraceContextPropagator();
22
+ const logger = new Logger("StandardTracerFastify");
23
+
24
+ export async function StandardTracerFastifyRegisterHooks(
25
+ fastify: FastifyInstance,
26
+ config: ConfigInterfaceOTel
27
+ ): Promise<void> {
28
+ fastify.addHook("onRequest", async (req) => {
29
+ if (req.url.indexOf("/api") !== 0) {
30
+ return;
31
+ }
32
+
33
+ let spanName = `${req.method}-${req.url}`;
34
+ let urlName = req.url;
35
+ if (config.OPENTELEMETRY_COLLECTOR_AWS) {
36
+ spanName = `${config.SERVICE_ID}-${config.VERSION}`;
37
+ urlName = `${config.SERVICE_ID}-${config.VERSION}-${req.method}-${req.url}`;
38
+ }
39
+ const callerContext = propagator.extract(
40
+ ROOT_CONTEXT,
41
+ req.headers,
42
+ defaultTextMapGetter
43
+ );
44
+ api.context.with(callerContext, () => {
45
+ const span = StandardTracerStartSpan(spanName);
46
+ span.setAttribute(ATTR_HTTP_REQUEST_METHOD, req.method);
47
+ span.setAttribute(ATTR_URL_PATH, urlName);
48
+ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
49
+ (req as any).tracerSpanApi = span;
50
+ });
51
+ });
52
+
53
+ fastify.addHook("onResponse", async (req, reply) => {
54
+ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
55
+ const span = (req as any).tracerSpanApi as Span;
56
+ if (reply.statusCode > 299) {
57
+ span.status.code = SpanStatusCode.ERROR;
58
+ } else {
59
+ span.status.code = SpanStatusCode.OK;
60
+ }
61
+ span.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, reply.statusCode);
62
+ span.end();
63
+ });
64
+
65
+ fastify.addHook("onError", async (req, reply, error) => {
66
+ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
67
+ const span = (req as any).tracerSpanApi as Span;
68
+ span.status.code = SpanStatusCode.ERROR;
69
+ span.recordException(error);
70
+ logger.error(error);
71
+ });
72
+ }
73
+
74
+ export function StandardTracerFastifyInit(fastify: FastifyInstance) {
75
+ fastify.addHook("onRequest", async (req) => {
76
+ const spanName = `${req.method}-${req.url}`;
77
+ const urlName = req.url;
78
+ const callerContext = propagator.extract(
79
+ ROOT_CONTEXT,
80
+ req.headers,
81
+ defaultTextMapGetter
82
+ );
83
+ api.context.with(callerContext, () => {
84
+ const span = StandardTracerStartSpan(spanName);
85
+ span.setAttribute(ATTR_HTTP_REQUEST_METHOD, req.method);
86
+ span.setAttribute(ATTR_URL_PATH, urlName);
87
+ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
88
+ (req as any).tracerSpanApi = span;
89
+ });
90
+ });
91
+
92
+ fastify.addHook("onResponse", async (req, reply) => {
93
+ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
94
+ const span = (req as any).tracerSpanApi as Span;
95
+ if (reply.statusCode > 299) {
96
+ span.status.code = SpanStatusCode.ERROR;
97
+ } else {
98
+ span.status.code = SpanStatusCode.OK;
99
+ }
100
+ span.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, reply.statusCode);
101
+ span.end();
102
+ });
103
+
104
+ fastify.addHook("onError", async (req, reply, error) => {
105
+ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
106
+ const span = (req as any).tracerSpanApi as Span;
107
+ span.status.code = SpanStatusCode.ERROR;
108
+ span.recordException(error);
109
+ });
110
+ }
package/src/Logger.ts DELETED
@@ -1,120 +0,0 @@
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
- }
@@ -1,91 +0,0 @@
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
- }
@@ -1,105 +0,0 @@
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
- }
@@ -1,11 +0,0 @@
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
- }