feat: standardize OpenTelemetry HTTP span names to include method and route pattern

This commit is contained in:
2025-08-27 10:17:24 -04:00
parent 00cb0d0421
commit f0c3bc6b9e

View File

@@ -10,6 +10,7 @@ import (
"net"
"net/http"
"os"
"regexp"
"strings"
"time"
@@ -25,11 +26,12 @@ import (
)
var (
httpMeter metric.Meter
httpTracer trace.Tracer
defReadTimeout = 10 * time.Second
defWriteTimeout = 10 * time.Second
defIdleTimeout = 15 * time.Second
httpMeter metric.Meter
httpTracer trace.Tracer
httpPatternWithMethodRegexp = regexp.MustCompile(`(\w+) .*`)
defReadTimeout = 10 * time.Second
defWriteTimeout = 10 * time.Second
defIdleTimeout = 15 * time.Second
)
func prepHTTPServer(opts *opts.AppHTTP) *http.Server {
@@ -84,12 +86,16 @@ func prepHTTPServer(opts *opts.AppHTTP) *http.Server {
}
}),
otelhttp.WithSpanNameFormatter(func(operation string, r *http.Request) string {
_, pattern := mux.Handler(r)
if pattern != "" {
return pattern // Use the route pattern as the span name, e.g., "/users/{id}"
endpoint := r.URL.Path
if _, pattern := mux.Handler(r); pattern != "" {
endpoint = pattern
}
// Fallback to the default naming convention if no route is found.
return operation + " " + r.URL.Path
if httpPatternWithMethodRegexp.MatchString(endpoint) {
return endpoint
}
return fmt.Sprintf("%s %s", r.Method, endpoint)
}))
// Set timeouts from defaults, override