package middleware import ( "log/slog" "time" "github.com/labstack/echo/v4" ) 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) uid, _ := c.Get(AuthUserIDKey).(string) attrs := []slog.Attr{ slog.String("request_id", rid), slog.String("method", c.Request().Method), slog.String("path", c.Request().URL.Path), slog.Int("status", status), slog.Int64("duration_ms", time.Since(start).Milliseconds()), slog.String("remote_ip", c.RealIP()), } if uid != "" { attrs = append(attrs, slog.String("user_id", uid)) } 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 } } }