Created
October 14, 2017 22:06
-
-
Save ndrewnee/6187a01427b9203b9f11ca5864b8a60d to your computer and use it in GitHub Desktop.
ZapLogger is an example of echo middleware that logs requests using logger "zap"
This file contains hidden or 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
package echomw | |
import ( | |
"time" | |
"github.com/labstack/echo" | |
"go.uber.org/zap" | |
"go.uber.org/zap/zapcore" | |
) | |
// ZapLogger is an example of echo middleware that logs requests using logger "zap" | |
func ZapLogger(log *zap.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) | |
} | |
fields := []zapcore.Field{ | |
zap.Int("status", res.Status), | |
zap.String("latency", time.Since(start).String()), | |
zap.String("id", id), | |
zap.String("method", req.Method), | |
zap.String("uri", req.RequestURI), | |
zap.String("host", req.Host), | |
zap.String("remote_ip", c.RealIP()), | |
} | |
n := res.Status | |
switch { | |
case n >= 500: | |
log.Error("Server error", fields...) | |
case n >= 400: | |
log.Warn("Client error", fields...) | |
case n >= 300: | |
log.Info("Redirection", fields...) | |
default: | |
log.Info("Success", fields...) | |
} | |
return nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment