Skip to content

Instantly share code, notes, and snippets.

@angelodlfrtr
Created February 18, 2022 14:09
Show Gist options
  • Select an option

  • Save angelodlfrtr/e529c20fac7d76e6713937f629fc118a to your computer and use it in GitHub Desktop.

Select an option

Save angelodlfrtr/e529c20fac7d76e6713937f629fc118a to your computer and use it in GitHub Desktop.
Gollang fiber zap logger
package middlewares
import (
"strconv"
"time"
"github.com/gofiber/fiber/v2"
"go.uber.org/zap"
)
// Logger middleware for fiber
func Logger(parent *zap.Logger) fiber.Handler {
return func(c *fiber.Ctx) error {
req := c.Request()
res := c.Response()
start := time.Now()
if err := c.Next(); err != nil {
return err
}
// Latency
latency := time.Since(start)
// Request id
requestID := string(req.Header.Peek(fiber.HeaderXRequestID))
// Request path
requestPath := string(req.URI().Path())
if requestPath == "" {
requestPath = "/"
}
// Bytes in
bytesIn := string(req.Header.Peek(fiber.HeaderContentLength))
if bytesIn == "" {
bytesIn = "0"
}
// Bytes out
bytesOut := string(res.Header.Peek(fiber.HeaderContentLength))
if bytesOut == "" {
bytesOut = "0"
}
// Log
parent.Info(
"request",
zap.String("remote_ip", c.IP()),
zap.Time("date", time.Now()),
zap.String("method", c.Method()),
zap.String("proto", c.Protocol()),
zap.Int("status", res.StatusCode()),
zap.String("bytes_in", bytesIn),
zap.String("bytes_out", bytesOut),
zap.String("latency_human", latency.String()),
zap.String("latency_ns", strconv.FormatInt(int64(latency), 10)),
zap.String("id", requestID),
zap.String("host", string(req.Host())),
zap.String("uri", string(req.RequestURI())),
zap.String("path", requestPath),
)
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment