forked from mtusi2026/mtusi2026lab6
ЛР 6 — БПИ2302 — Нурлыгаянова — на 3
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
const AuthUserIDKey = "caller_id"
|
||||
|
||||
func Logger(logger *slog.Logger) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
start := time.Now()
|
||||
if err := next(c); err != nil {
|
||||
c.Error(err)
|
||||
}
|
||||
status := c.Response().Status
|
||||
|
||||
rid, _ := c.Get(RequestIDKey).(string)
|
||||
sc := trace.SpanContextFromContext(c.Request().Context())
|
||||
|
||||
attrs := []slog.Attr{
|
||||
slog.String("request_id", rid),
|
||||
slog.String("method", c.Request().Method),
|
||||
slog.String("route", c.Path()),
|
||||
slog.Int("status", status),
|
||||
slog.Int64("duration_ms", time.Since(start).Milliseconds()),
|
||||
slog.String("event", "http.request"),
|
||||
slog.String("trace_id", sc.TraceID().String()),
|
||||
slog.String("span_id", sc.SpanID().String()),
|
||||
}
|
||||
|
||||
level := slog.LevelInfo
|
||||
switch {
|
||||
case status >= 500:
|
||||
level = slog.LevelError
|
||||
case status >= 400:
|
||||
level = slog.LevelWarn
|
||||
}
|
||||
logger.LogAttrs(c.Request().Context(), level, "http request", attrs...)
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user