feat(otel): Added support for W3C Trace Context format (#1151)

* feat(otel): Added support for W3C Trace Context format

* removed unneeded HonoRequest
pull/1152/head
Nicholas Dobie 2025-05-07 17:20:02 -05:00 committed by GitHub
parent 0debb59474
commit 414f0a6c95
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 13 additions and 1 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/otel': minor
---
Added support for W3C Trace Context format

View File

@ -1,5 +1,5 @@
import type { TracerProvider } from '@opentelemetry/api'
import { SpanKind, SpanStatusCode, trace } from '@opentelemetry/api'
import { SpanKind, SpanStatusCode, trace, context, propagation } from '@opentelemetry/api'
import {
ATTR_HTTP_REQUEST_HEADER,
ATTR_HTTP_REQUEST_METHOD,
@ -42,6 +42,12 @@ export const otel = <E extends Env = any, P extends string = any, I extends Inpu
const tracerProvider = options.tracerProvider ?? trace.getTracerProvider()
const tracer = tracerProvider.getTracer(PACKAGE_NAME, PACKAGE_VERSION)
return createMiddleware<E, P, I>(async (c, next) => {
// Handle propagation of trace context from a request using the W3C Trace Context format
let activeContext = context.active()
if (c.req.header('traceparent')) {
activeContext = propagation.extract(context.active(), c.req.header())
}
const routePath = c.req.routePath
await tracer.startActiveSpan(
`${c.req.method} ${c.req.routePath}`,
@ -53,6 +59,7 @@ export const otel = <E extends Env = any, P extends string = any, I extends Inpu
[ATTR_HTTP_ROUTE]: routePath,
},
},
activeContext,
async (span) => {
for (const [name, value] of Object.entries(c.req.header())) {
span.setAttribute(ATTR_HTTP_REQUEST_HEADER(name), value)