Skip to content

Instantly share code, notes, and snippets.

@ndrewnee
Created October 14, 2017 22:06
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ndrewnee/6187a01427b9203b9f11ca5864b8a60d to your computer and use it in GitHub Desktop.
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"
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