All files / src instrumentation.node.ts

0% Statements 0/28
0% Branches 0/18
0% Functions 0/9
0% Lines 0/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162                                                                                                                                                                                                                                                                                                                                   
/**
 * This file initializes OpenTelemetry for the application using the @opentelemetry/sdk-node package.
 *
 * Two Dynatrace exporters are provided, and rely on the following (optional) environment variables:
 *
 * <ul>
 *   <li>
 *     OTEL_METRICS_ENDPOINT -- defines the Dynatrace OpenTelemetry metrics endpoint
 *     (ex: https://example.com/e/00000000-0000-0000-0000-000000000000/api/v2/otlp/v1/metrics)
 *   </li>
 *   <li>
 *   - OTEL_TRACES_ENDPOINT -- defines the Dynatrace Opentelemetry traces endpoint
 *     (ex: https://example.com/e/00000000-0000-0000-0000-000000000000/api/v2/otlp/v1/traces)
 *   </li>
 *   <li>
 *   - OTEL_API_KEY -- defines the Dynatrace API key used by the metrics and traces endpoint
 *   </li>
 * </ul>
 *
 * If either Dynatrace endpoint is not provided, a NOOP metrics and/or a NOOP traces exporter will be configured.
 *
 * NOTE: to ensure that tracing is fully initialized, NodeSDK must be initialized early during runtime.
 * For Next.js, this can be done by importing this file in next.config.js.
 *
 * NOTE: because of limitations in the Next.js runtimes, metrics cannot be emitted from middleware.
 *
 * References:
 *
 * <ul>
 *   <li>https://www.npmjs.com/package/@opentelemetry/sdk-node</li>
 *   <li>https://www.dynatrace.com/support/help/extend-dynatrace/opentelemetry</li>
 *   <li>https://nextjs.org/docs/api-reference/edge-runtime</li>
 * </ul>
 */
import { ExportResultCode } from '@opentelemetry/core'
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-proto'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'
import { CompressionAlgorithm } from '@opentelemetry/otlp-exporter-base'
import {
  Resource,
  envDetector,
  hostDetector,
  osDetector,
  processDetector,
} from '@opentelemetry/resources'
import {
  AggregationTemporality,
  PeriodicExportingMetricReader,
  PushMetricExporter,
} from '@opentelemetry/sdk-metrics'
import { NodeSDK } from '@opentelemetry/sdk-node'
import { SpanExporter } from '@opentelemetry/sdk-trace-base'
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'
 
import { getLogger } from './logging/log-util'
 
const logger = getLogger('instrumentation.node')
 
const getMetricExporter = (): PushMetricExporter => {
  const exportMetrics = process.env.OTEL_METRICS_ENDPOINT
 
  if (exportMetrics) {
    if (!process.env.OTEL_API_KEY) {
      throw new Error(
        'OTEL_API_KEY must be configured when OTEL_METRICS_ENDPOINT is set',
      )
    }
 
    logger.info(
      `Exporting metrics to ${
        process.env.OTEL_METRICS_ENDPOINT
      } every ${getMetricExportInterval()} ms`,
    )
 
    return new OTLPMetricExporter({
      compression: CompressionAlgorithm.GZIP,
      headers: { Authorization: `Api-Token ${process.env.OTEL_API_KEY}` },
      temporalityPreference: AggregationTemporality.DELTA,
      url: process.env.OTEL_METRICS_ENDPOINT,
    })
  }
 
  logger.info(
    'Metrics exporting is disabled; set OTEL_METRICS_ENDPOINT to enable.',
  )
 
  return {
    // a no-op PushMetricExporter implementation
    export: (metrics, resultCallback) =>
      resultCallback({ code: ExportResultCode.SUCCESS }),
    forceFlush: async () => {},
    shutdown: async () => {},
  }
}
 
const getMetricExportInterval = () => {
  return parseInt(process.env.OTEL_METRICS_EXPORT_INTERVAL_MILLIS ?? '60000')
}
 
const getMetricTimeout = () => {
  return parseInt(process.env.OTEL_METRICS_EXPORT_TIMEOUT_MILLIS ?? '30000')
}
 
const getTraceExporter = (): SpanExporter => {
  const exportTraces = process.env.OTEL_TRACES_ENDPOINT
 
  if (exportTraces) {
    if (!process.env.OTEL_API_KEY) {
      throw new Error(
        'OTEL_API_KEY must be configured when OTEL_TRACES_ENDPOINT is set',
      )
    }
 
    logger.info(
      `Exporting traces to ${process.env.OTEL_TRACES_ENDPOINT} every 30000 ms`,
    )
 
    return new OTLPTraceExporter({
      compression: CompressionAlgorithm.GZIP,
      headers: { Authorization: `Api-Token ${process.env.OTEL_API_KEY}` },
      url: process.env.OTEL_TRACES_ENDPOINT,
    })
  }
 
  logger.info(
    'Traces exporting is disabled; set OTEL_TRACES_ENDPOINT to enable.',
  )
 
  return {
    // a no-op SpanExporter implementation
    export: (spans, resultCallback) =>
      resultCallback({ code: ExportResultCode.SUCCESS }),
    shutdown: async () => {},
  }
}
 
logger.info(`Initializing OpenTelemetry SDK...`)
 
const sdk = new NodeSDK({
  metricReader: new PeriodicExportingMetricReader({
    exporter: getMetricExporter(),
    exportIntervalMillis: getMetricExportInterval(),
    exportTimeoutMillis: getMetricTimeout(),
  }),
  resource: new Resource({
    // Note: any attributes added here must be configured in Dynatrace under
    // Settings → Metrics → OpenTelemetry metrics → Allow list: resource and scope attributes
    //
    // see: node_modules/@opentelemetry/semantic-conventions/build/src/resource/SemanticResourceAttributes.js
    // see: node_modules/@opentelemetry/semantic-conventions/build/src/trace/SemanticResourceAttributes.js
    [SemanticResourceAttributes.DEPLOYMENT_ENVIRONMENT]:
      process.env.OTEL_ENVIRONMENT ?? 'local',
    [SemanticResourceAttributes.SERVICE_NAME]:
      process.env.OTEL_SERVICE_NAME ?? 'next-template',
    [SemanticResourceAttributes.SERVICE_VERSION]:
      process.env.BUILD_VERSION ?? '00000000-0000-00000000',
  }),
  resourceDetectors: [envDetector, hostDetector, osDetector, processDetector],
  traceExporter: getTraceExporter(),
})
sdk.start()