From 768a999ffe99d08e4992cdc01de22d59150d6b5a Mon Sep 17 00:00:00 2001 From: "samuel.ochsner" Date: Thu, 20 Jun 2024 13:06:37 +0200 Subject: [PATCH] chore: Add SpanEnrichingProcessor for Azure Monitor integration --- src/instrumentation.ts | 2 ++ src/next.config.js | 2 +- src/span-enriching-processor.ts | 23 +++++++++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 src/span-enriching-processor.ts diff --git a/src/instrumentation.ts b/src/instrumentation.ts index 89a6e9f17..df211ec58 100644 --- a/src/instrumentation.ts +++ b/src/instrumentation.ts @@ -4,6 +4,7 @@ export function register() { if (process.env.NEXT_RUNTIME === 'nodejs') { const { useAzureMonitor } = require("@azure/monitor-opentelemetry"); const { metrics } = require('@opentelemetry/api'); + const { SpanEnrichingProcessor } = require('./span-enriching-processor'); const cosmosdb = new URL(process.env.AZURE_COSMOSDB_URI); const cosmosdbHost = cosmosdb.hostname; @@ -30,6 +31,7 @@ export function register() { }; useAzureMonitor({ + spanProcessors: [new SpanEnrichingProcessor()] , azureMonitorExporterOptions: { connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "", diff --git a/src/next.config.js b/src/next.config.js index f82dfa9af..9b62abaad 100644 --- a/src/next.config.js +++ b/src/next.config.js @@ -2,7 +2,7 @@ const nextConfig = { output: "standalone", experimental: { - serverComponentsExternalPackages: ["@azure/storage-blob", "@azure/monitor-opentelemetry", "@opentelemetry/api", "@opentelemetry/instrumentation"], + serverComponentsExternalPackages: ["@azure/storage-blob", "@azure/monitor-opentelemetry", "@opentelemetry/api", "@opentelemetry/instrumentation", "@opentelemetry/sdk-trace-base"], instrumentationHook: true, } }; diff --git a/src/span-enriching-processor.ts b/src/span-enriching-processor.ts new file mode 100644 index 000000000..afc122617 --- /dev/null +++ b/src/span-enriching-processor.ts @@ -0,0 +1,23 @@ +// Import the necessary packages. +import { SpanKind, TraceFlags } from "@opentelemetry/api"; +import { Span, SpanProcessor } from "@opentelemetry/sdk-trace-base"; + +// Create a new SpanEnrichingProcessor class. +export class SpanEnrichingProcessor implements SpanProcessor { + forceFlush(): Promise { + return Promise.resolve(); + } + + shutdown(): Promise { + return Promise.resolve(); + } + + onStart(_span: Span): void {} + + onEnd(span: Span) { + // If the span is an internal span, set the trace flags to NONE to prevent it from being collected. + if(span.kind == SpanKind.INTERNAL){ + span.spanContext().traceFlags = TraceFlags.NONE; + } + } +} \ No newline at end of file