Created
July 9, 2020 09:47
-
-
Save khash/55c6aae92ba7353ffd2b416e7ad2da76 to your computer and use it in GitHub Desktop.
Simple Echo middleware to log to Zerolog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// simple Echo middleware to log to Zerolog | |
package utils | |
import ( | |
"time" | |
"github.com/labstack/echo" | |
"github.com/rs/zerolog" | |
) | |
func ZeroLogger(log zerolog.Logger) echo.MiddlewareFunc { | |
return func(next echo.HandlerFunc) echo.HandlerFunc { | |
return func(c echo.Context) error { | |
start := time.Now() | |
err := next(c) | |
if err != nil { | |
c.Error(err) | |
} | |
req := c.Request() | |
res := c.Response() | |
id := req.Header.Get(echo.HeaderXRequestID) | |
if id == "" { | |
id = res.Header().Get(echo.HeaderXRequestID) | |
} | |
level := log.GetLevel() | |
n := res.Status | |
switch { | |
case n >= 500: | |
level = zerolog.ErrorLevel | |
case n >= 400: | |
level = zerolog.WarnLevel | |
case n >= 300: | |
level = zerolog.InfoLevel | |
default: | |
level = zerolog.InfoLevel | |
} | |
log.WithLevel(level). | |
Int("status", res.Status). | |
Str("latency", time.Since(start).String()). | |
Str("id", id). | |
Str("method", req.Method). | |
Str("uri", req.RequestURI). | |
Str("host", req.Host). | |
Str("remote_ip", c.RealIP()). | |
Msg("request") | |
return nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment