set span name and attributes after the request is handled

pull/1113/head
Milo Hansen 2025-04-08 12:09:41 -07:00
parent 5315ef7e0d
commit a638a15346
1 changed files with 15 additions and 9 deletions

View File

@ -15,11 +15,13 @@ import metadata from '../package.json' with { type: 'json'}
const PACKAGE_NAME = metadata.name const PACKAGE_NAME = metadata.name
const PACKAGE_VERSION = metadata.version const PACKAGE_VERSION = metadata.version
export type OtelOptions = { export type OtelOptions =
augmentSpan?: false; | {
augmentSpan?: false
tracerProvider?: TracerProvider tracerProvider?: TracerProvider
} | { }
augmentSpan: true; | {
augmentSpan: true
} }
export const otel = <E extends Env = any, P extends string = any, I extends Input = {}>( export const otel = <E extends Env = any, P extends string = any, I extends Input = {}>(
@ -42,7 +44,7 @@ export const otel = <E extends Env = any, P extends string = any, I extends Inpu
return createMiddleware<E, P, I>(async (c, next) => { return createMiddleware<E, P, I>(async (c, next) => {
const routePath = c.req.routePath const routePath = c.req.routePath
await tracer.startActiveSpan( await tracer.startActiveSpan(
`${c.req.method} ${routePath}`, `${c.req.method} ${c.req.routePath}`,
{ {
kind: SpanKind.SERVER, kind: SpanKind.SERVER,
attributes: { attributes: {
@ -57,6 +59,10 @@ export const otel = <E extends Env = any, P extends string = any, I extends Inpu
} }
try { try {
await next() await next()
// Update the span name and route path now that we have the response
// because the route path may have changed
span.updateName(`${c.req.method} ${c.req.routePath}`)
span.setAttribute(ATTR_HTTP_ROUTE, c.req.routePath)
span.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, c.res.status) span.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, c.res.status)
for (const [name, value] of c.res.headers.entries()) { for (const [name, value] of c.res.headers.entries()) {
span.setAttribute(ATTR_HTTP_RESPONSE_HEADER(name), value) span.setAttribute(ATTR_HTTP_RESPONSE_HEADER(name), value)