|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const { trace, SpanKind, context } = require('@opentelemetry/api'); |
| 4 | +const { AlwaysOnSampler } = require('@opentelemetry/sdk-trace-node'); |
| 5 | +const express = require('express'); |
| 6 | +const process = require('process'); |
| 7 | +const opentelemetry = require("@opentelemetry/sdk-node"); |
| 8 | +const { SimpleSpanProcessor } = require('@opentelemetry/sdk-trace-base'); |
| 9 | +const { AWSXRayPropagator } = require("@opentelemetry/propagator-aws-xray"); |
| 10 | +const { AWSXRayIdGenerator } = require("@opentelemetry/id-generator-aws-xray"); |
| 11 | +const { OTLPUdpSpanExporter } = require("@aws/aws-otel-otlp-udp-exporter") |
| 12 | + |
| 13 | +const _traceExporter = new OTLPUdpSpanExporter(); |
| 14 | +const _spanProcessor = new SimpleSpanProcessor(_traceExporter); |
| 15 | + |
| 16 | +const PORT = parseInt(process.env.SAMPLE_APP_PORT || '8080', 10); |
| 17 | +const app = express(); |
| 18 | + |
| 19 | +app.get('/', (req, res) => { |
| 20 | + res.send(`healthcheck`) |
| 21 | +}); |
| 22 | + |
| 23 | +app.get('/test', (req, res) => { |
| 24 | + const tracer = trace.getTracer("testTracer"); |
| 25 | + let ctx = context.active(); |
| 26 | + let span = tracer.startSpan("testSpan", {kind: SpanKind.SERVER}, ctx); |
| 27 | + let traceId = span.spanContext().traceId; |
| 28 | + span.end(); |
| 29 | + let xrayFormatTraceId = "1-" + traceId.substring(0,8) + "-" + traceId.substring(8); |
| 30 | + console.log(`X-Ray Trace ID is: ${xrayFormatTraceId}`); |
| 31 | + |
| 32 | + res.send(`${xrayFormatTraceId}`); |
| 33 | +}); |
| 34 | + |
| 35 | +app.listen(PORT, async () => { |
| 36 | + await nodeSDKBuilder(); |
| 37 | + console.log(`Listening for requests on http://localhost:${PORT}`); |
| 38 | +}); |
| 39 | + |
| 40 | +async function nodeSDKBuilder() { |
| 41 | + const sdk = new opentelemetry.NodeSDK({ |
| 42 | + textMapPropagator: new AWSXRayPropagator(), |
| 43 | + instrumentations: [], |
| 44 | + spanProcessor: _spanProcessor, |
| 45 | + sampler: new AlwaysOnSampler(), |
| 46 | + idGenerator: new AWSXRayIdGenerator(), |
| 47 | + }); |
| 48 | + |
| 49 | + // this enables the API to record telemetry |
| 50 | + await sdk.start(); |
| 51 | + |
| 52 | + // gracefully shut down the SDK on process exit |
| 53 | + process.on('SIGTERM', () => { |
| 54 | + sdk.shutdown() |
| 55 | + .then(() => console.log('Tracing terminated')) |
| 56 | + .catch((error) => console.log('Error terminating tracing', error)) |
| 57 | + .finally(() => process.exit(0)); |
| 58 | + }); |
| 59 | +} |
0 commit comments