package httpx import ( "strconv" "strings" "time" "github.com/gin-gonic/gin" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/trace" "messenger/internal/platform/telemetry" ) func businessTelemetry() gin.HandlerFunc { m := otel.Meter("messenger.http") requests, _ := m.Int64Counter("messenger.http.requests") duration, _ := m.Float64Histogram("messenger.http.duration", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(.001, .005, .01, .025, .05, .1, .25, .5, 1, 2, 5, 10)) tracer := otel.Tracer("messenger.http") return func(c *gin.Context) { route := c.FullPath() if !strings.HasPrefix(route, "/api/v1/") { c.Next() return } method := c.Request.Method parent := otel.GetTextMapPropagator().Extract(c.Request.Context(), propagation.HeaderCarrier(c.Request.Header)) ctx, span := tracer.Start(parent, method+" "+route, trace.WithSpanKind(trace.SpanKindServer)) defer span.End() c.Request = c.Request.WithContext(ctx) start := time.Now() c.Next() status := c.Writer.Status() attrs := []attribute.KeyValue{attribute.String("method", method), attribute.String("route", route), attribute.String("status_class", strconv.Itoa(status/100)+"xx")} opts := metric.WithAttributes(attrs...) requests.Add(ctx, 1, opts) duration.Record(ctx, time.Since(start).Seconds(), opts) attrs = append(attrs, attribute.String("request_id", RequestID(c))) span.SetAttributes(attrs...) if status >= 500 { span.SetStatus(codes.Error, "server_error") } telemetry.Event(ctx, "http.request", attrs...) } }