forked from mtusi2026/mtusi2026lab6
Реализовать наблюдаемость мессенджера для ЛР 6 на четыре
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"highload/internal/observability"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
otellog "go.opentelemetry.io/otel/log"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
type responseWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (w *responseWriter) WriteHeader(status int) {
|
||||
w.status = status
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (w *responseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
|
||||
|
||||
func (m *Middleware) Logging(next http.Handler, routeFor func(*http.Request) string) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
method := "OTHER"
|
||||
switch r.Method {
|
||||
case http.MethodGet, http.MethodHead, http.MethodPost, http.MethodDelete, http.MethodOptions:
|
||||
method = r.Method
|
||||
}
|
||||
route := routeFor(r)
|
||||
ctx := observability.WithRequestID(r.Context(), RequestIDFromContext(r.Context()))
|
||||
health := route == "/health/live" || route == "/health/ready"
|
||||
var span trace.Span
|
||||
if !health {
|
||||
ctx = observability.W3C.Extract(ctx, propagation.HeaderCarrier(r.Header))
|
||||
ctx, span = observability.Tracer.Start(ctx, method+" "+route, trace.WithSpanKind(trace.SpanKindServer),
|
||||
trace.WithAttributes(attribute.String("http.request.method", method), attribute.String("http.route", route)))
|
||||
defer span.End()
|
||||
}
|
||||
rw := &responseWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(rw, r.WithContext(ctx))
|
||||
elapsed := time.Since(start)
|
||||
observability.ObserveHTTP(ctx, method, route, rw.status, elapsed)
|
||||
if span != nil {
|
||||
level := otellog.SeverityInfo
|
||||
span.SetAttributes(attribute.Int("http.response.status_code", rw.status))
|
||||
if rw.status >= 500 {
|
||||
span.SetStatus(codes.Error, "server_error")
|
||||
level = otellog.SeverityError
|
||||
}
|
||||
observability.Log(ctx, "http.request", level, attribute.String("method", method),
|
||||
attribute.String("route", route), attribute.Int("status", rw.status),
|
||||
attribute.Float64("duration_seconds", elapsed.Seconds()))
|
||||
}
|
||||
slog.Info("http request", "method", method, "route", route, "status", rw.status,
|
||||
"duration", elapsed, "request_id", RequestIDFromContext(ctx))
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user