Repository navigation
fix(telemetry): instrument v3 API routes with tracing - #4468
gergely-kurucz-konghq merged 7 commits into
Conversation
The v3 router group was registered before RouterHooks.Middlewares were
applied, so v3 routes had no otelhttp instrumentation while v1 did. Apply
the hook middlewares to the v3 group as well (via collectMiddlewareHooks),
giving v3 the same tracing and metrics as v1.
Span naming:
- Server span is named "METHOD /route/{template}" from chi's resolved
route pattern, which is already available when otelhttp's
WithSpanNameFormatter runs. Path params render as "{param}", so both
ULID ids and arbitrary entity keys collapse to a low-cardinality name.
Falls back to a ULID-collapsed raw path for unmatched routes (404s).
- The exact template is also recorded on the http.route attribute and
metric label (the canonical low-cardinality routing dimension).
- Each handler opens an application-level child span named after its
operation (httptransport.WithOperationName), nested under the server
span and parenting downstream DB spans. The server span captures the
full HTTP-boundary timing (incl. middleware); the operation span
captures app logic — the delta surfaces middleware overhead.
Note: otelhttp fixes the span name at tracer.Start, and a post-start
SetName on the server span is a no-op in this chi setup, which is why the
name is derived in the formatter rather than after routing.
📝 WalkthroughWalkthroughAdds low-cardinality server span naming and explicit http.route attribution, exposes a global toggle and handler-level per-operation spans, materializes router-hook middlewares for reuse, and adds config + tests for low-cardinality path behavior. ChangesOpenTelemetry Span Instrumentation and Middleware Hook Collection
🎯 3 (Moderate) | ⏱️ ~25 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
openmeter/server/server.go (2)
108-108: ⚖️ Poor tradeoffHeads-up on the
slog.Default()fallback.This mirrors the existing v1 setup, so no behavior regression — but as per coding guidelines, production initialization shouldn't lean on
slog.Default()as a fallback; the logger should be injected via config/provider inputs. If you do the shared-builder extraction above, that's a natural spot to thread an explicit*slog.Loggerthrough instead.As per coding guidelines: "In production constructors and initialization, do not use
slog.Default()as a fallback; require a*slog.Loggerin config/provider inputs and inject it explicitly".🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/server/server.go` at line 108, The code currently uses slog.Default().Handler() inside server.NewRequestLoggerMiddleware which relies on a global fallback; change the constructor/initialization to accept and propagate an explicit *slog.Logger from your config/provider and pass its Handler to NewRequestLoggerMiddleware instead of calling slog.Default(), e.g., add a logger field to the shared builder/provider and thread that *slog.Logger into the call site so NewRequestLoggerMiddleware receives an injected logger handler rather than using slog.Default().
95-110: ⚡ Quick winNice fix wiring v3 into the same instrumentation! Consider sharing the standard middleware chain.
The construction here works (you're appending to a freshly returned slice, so no aliasing surprises 👍). One thing worth tidying: the standard chain (
RealIP,RequestID, thecontextxattrs wrapper, request logger,Recoverer) is now defined twice — here for v3 and again in the v1 group at Lines 167-178. They're identical today, but they can quietly drift apart later. Extracting a tiny builder keeps both groups honest.♻️ One shared builder for both groups
func standardMiddlewares() []server.MiddlewareFunc { return []server.MiddlewareFunc{ middleware.RealIP, middleware.RequestID, func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() ctx = contextx.WithAttrs(ctx, server.GetRequestAttributes(r)) h.ServeHTTP(w, r.WithContext(ctx)) }) }, server.NewRequestLoggerMiddleware(slog.Default().Handler()), middleware.Recoverer, } }Then here:
- v3Middlewares := append(collectMiddlewareHooks(config.RouterHooks.Middlewares), []server.MiddlewareFunc{ - middleware.RealIP, - middleware.RequestID, - func(h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - ctx = contextx.WithAttrs(ctx, server.GetRequestAttributes(r)) - - h.ServeHTTP(w, r.WithContext(ctx)) - }) - }, - server.NewRequestLoggerMiddleware(slog.Default().Handler()), - middleware.Recoverer, - }...) + v3Middlewares := append(collectMiddlewareHooks(config.RouterHooks.Middlewares), standardMiddlewares()...)And the v1 group can reuse it via
for _, mw := range standardMiddlewares() { r.Use(mw) }.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/server/server.go` around lines 95 - 110, Extract the duplicated standard middleware slice into a single helper (e.g. standardMiddlewares()) that returns []server.MiddlewareFunc containing middleware.RealIP, middleware.RequestID, the contextx.WithAttrs wrapper, server.NewRequestLoggerMiddleware(slog.Default().Handler()), and middleware.Recoverer; then replace the inline slice usage in v3Middlewares (currently built with append(collectMiddlewareHooks(...), []server.MiddlewareFunc{...}...)) and the identical middleware list used for the v1 router group by calling/iterating over standardMiddlewares() (use append(..., standardMiddlewares()...) for v3 and for v1 call r.Use for each mw from standardMiddlewares()) so both groups share the same source of truth.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@app/common/telemetry.go`:
- Line 289: The span attribute is using r.URL.String() which can include the
query string; update the span.SetAttributes call in the telemetry wrapper (the
line with span.SetAttributes(semconv.URLPath(r.URL.String()),
semconv.HTTPRoute(routePattern))) to pass semconv.URLPath(r.URL.Path) instead to
record only the path component (avoiding query-derived cardinality and PII
leakage) while keeping semconv.HTTPRoute(routePattern) unchanged.
- Around line 298-311: The span-name formatter currently reads
chi.RouteContext() too early (otelhttp.WithSpanNameFormatter runs before routing
completes) so RoutePattern() is usually empty; update the logic so the route
template is resolved after routing (e.g., set the span name inside
middleware/after calling next.ServeHTTP or rely on chi's middleware that sets
the template) rather than in otelhttp.WithSpanNameFormatter, and ensure
lowCardinalityPath can handle non-ULID param placeholders; also change any
semconv.URLPath usage to use r.URL.Path (not r.URL.String()) to avoid including
query params. Reference: otelhttp.WithSpanNameFormatter, lowCardinalityPath,
chi.RouteContext/RoutePattern, and semconv.URLPath.
---
Nitpick comments:
In `@openmeter/server/server.go`:
- Line 108: The code currently uses slog.Default().Handler() inside
server.NewRequestLoggerMiddleware which relies on a global fallback; change the
constructor/initialization to accept and propagate an explicit *slog.Logger from
your config/provider and pass its Handler to NewRequestLoggerMiddleware instead
of calling slog.Default(), e.g., add a logger field to the shared
builder/provider and thread that *slog.Logger into the call site so
NewRequestLoggerMiddleware receives an injected logger handler rather than using
slog.Default().
- Around line 95-110: Extract the duplicated standard middleware slice into a
single helper (e.g. standardMiddlewares()) that returns []server.MiddlewareFunc
containing middleware.RealIP, middleware.RequestID, the contextx.WithAttrs
wrapper, server.NewRequestLoggerMiddleware(slog.Default().Handler()), and
middleware.Recoverer; then replace the inline slice usage in v3Middlewares
(currently built with append(collectMiddlewareHooks(...),
[]server.MiddlewareFunc{...}...)) and the identical middleware list used for the
v1 router group by calling/iterating over standardMiddlewares() (use append(...,
standardMiddlewares()...) for v3 and for v1 call r.Use for each mw from
standardMiddlewares()) so both groups share the same source of truth.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 805d079e-fd90-48b4-b2d1-9aa10a0a50cb
📒 Files selected for processing (3)
app/common/telemetry.goopenmeter/server/server.gopkg/framework/transport/httptransport/handler.go
Use r.URL.Path instead of r.URL.String() for the url.path span attribute to avoid query-string cardinality and potential PII in traces.
mark-vass-konghq
left a comment
There was a problem hiding this comment.
I didn’t find a clear merge-blocking bug. Possible improvements I’d consider
Build the hook middleware slice a single time and apply it to both the v3 and v1 groups, instead of re-invoking the hook functions per group. Avoids running hook bodies twice — harmless for telemetry, unsafe for future hooks with construction side effects.
otelhttp's post-handler pass surfaces r.Pattern as the sub-router mount
prefix ("/api/v3/*"), which leaked into v3 span names. Skip any "*"-bearing
route from all sources (r.Pattern, chi RoutePattern) and fall back to the
ULID-collapsed path. Also document otelhttp's two-pass formatter behavior.
lowCardinalityPath only masked ULIDs, so arbitrary slugs/keys/tokens from v3 (mount-wildcard fallback) and unmatched/scanner traffic leaked into span names. Also mask UUIDs, numeric ids, and over-long opaque segments, and truncate pathologically deep paths. Add unit tests.
The application-level per-operation child span was emitted for every httptransport handler with an operation name — v1/v2/v3 alike — adding a span to nearly every request. Make it a global, default-off switch (telemetry.trace.operationSpans) applied once at trace init via httptransport.EnableOperationSpans, so the extra span volume is a deliberate per-env opt-in. The http.route attribute is still set regardless.
There was a problem hiding this comment.
🧹 Nitpick comments (2)
app/common/telemetry_test.go (1)
13-65: ⚡ Quick winAdd one test around the actual formatter path selection.
These cases pin
lowCardinalityPath, but the fragile bit in this PR is theWithSpanNameFormatterdecision tree (r.Patternvs chiRoutePatternvs wildcard skip vs fallback). A small request-level test aroundNewTelemetryRouterHookwould give you coverage for the behavior that actually fixes v3 naming. As per coding guidelines,**/*_test.go: "Make sure the tests are comprehensive and cover the changes."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/common/telemetry_test.go` around lines 13 - 65, Add a test that exercises the formatter selection logic in NewTelemetryRouterHook: create a chi router with routes that set r.Pattern and some that rely on chi's RoutePattern (use route parameters and a wildcard route), install NewTelemetryRouterHook (or call WithSpanNameFormatter path selection) and send test requests to verify the produced span name uses the correct formatter (lowCardinalityPath vs pattern-based vs skipped wildcard) — assert the final span name equals the expected string for each case; reference NewTelemetryRouterHook, WithSpanNameFormatter, lowCardinalityPath, r.Pattern and RoutePattern in the test so it covers the decision tree described in the review.pkg/framework/transport/httptransport/handler.go (1)
35-39: ⚡ Quick winPlease add a unit test for the global toggle behavior.
This change is broad enough that it’s worth pinning both modes: with
EnableOperationSpans(false)no extra child span should be created, and with it enabled you should get exactly one operation child span under the server span. That keeps this package-level switch from becoming order-dependent or silently regressing later. As per coding guidelines,**/*_test.go: "Make sure the tests are comprehensive and cover the changes."Also applies to: 105-115
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/framework/transport/httptransport/handler.go` around lines 35 - 39, Add a new *_test.go that verifies the package-level toggle by calling EnableOperationSpans(false) and EnableOperationSpans(true), resetting operationSpansEnabled as needed between cases, then exercising the HTTP handler code path that produces a server span (e.g., invoking the handler's ServeHTTP or the function that starts the server span) while using an in-memory/testing OpenTelemetry exporter/tracer to capture spans; assert that when disabled there are zero operation child spans under the server span and when enabled there is exactly one operation child span. Ensure the test isolates global state (restore/reset operationSpansEnabled) and uses deterministic span collection so it fails if the toggle is order-dependent or regresses.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@app/common/telemetry_test.go`:
- Around line 13-65: Add a test that exercises the formatter selection logic in
NewTelemetryRouterHook: create a chi router with routes that set r.Pattern and
some that rely on chi's RoutePattern (use route parameters and a wildcard
route), install NewTelemetryRouterHook (or call WithSpanNameFormatter path
selection) and send test requests to verify the produced span name uses the
correct formatter (lowCardinalityPath vs pattern-based vs skipped wildcard) —
assert the final span name equals the expected string for each case; reference
NewTelemetryRouterHook, WithSpanNameFormatter, lowCardinalityPath, r.Pattern and
RoutePattern in the test so it covers the decision tree described in the review.
In `@pkg/framework/transport/httptransport/handler.go`:
- Around line 35-39: Add a new *_test.go that verifies the package-level toggle
by calling EnableOperationSpans(false) and EnableOperationSpans(true), resetting
operationSpansEnabled as needed between cases, then exercising the HTTP handler
code path that produces a server span (e.g., invoking the handler's ServeHTTP or
the function that starts the server span) while using an in-memory/testing
OpenTelemetry exporter/tracer to capture spans; assert that when disabled there
are zero operation child spans under the server span and when enabled there is
exactly one operation child span. Ensure the test isolates global state
(restore/reset operationSpansEnabled) and uses deterministic span collection so
it fails if the toggle is order-dependent or regresses.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 7bec728e-eb89-4ae8-aa00-85e878481e77
📒 Files selected for processing (5)
app/common/telemetry.goapp/common/telemetry_test.goapp/config/telemetry.goopenmeter/server/server.gopkg/framework/transport/httptransport/handler.go
🚧 Files skipped from review as they are similar to previous changes (1)
- openmeter/server/server.go
What
Instruments the v3 API with OpenTelemetry HTTP tracing/metrics (on par with v1), gives server spans meaningful low-cardinality names, and adds an optional per-operation child span behind a global toggle.
Why
v3 routes had no otelhttp instrumentation (the v3 group was registered before the telemetry middleware), and server spans had empty/unhelpful names — making v3 traces hard to find and group. We also wanted handler-vs-middleware timing visibility without inflating span volume across the whole API.
How
METHOD /route/{template}from the chi route pattern (r.Pattern→ chiRouteContext→ fallback). Unresolved mount wildcards (/api/v3/*) are skipped.http.routeattribute + metric label: the exact route template — the canonical low-cardinality routing dimension.url.pathis path-only (no query string).:id, and truncates pathologically deep paths — so unmatched/scanner traffic can't blow up span-name cardinality.list-customers), nested under the server span, exposing the middleware-vs-handler split. Off by default, enabled viatelemetry.trace.operationSpans, since it adds a span to every request.Summary by CodeRabbit