Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Alternative logging through zap #129

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions ginzap/example/example.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package main

import (
"fmt"
"time"

"github.com/uber-go/zap"
"github.com/gin-gonic/contrib/ginzap"
"github.com/gin-gonic/gin"
)

func main() {
r := gin.New()

log := zap.New(
zap.NewTextEncoder(),
zap.DebugLevel,
)

// Add a ginzap middleware, which:
// - Logs all requests, like a combined access and error log.
// - Logs to stdout.
// - RFC3339 with UTC time format.
r.Use(ginzap.Ginzap(log, time.RFC3339, true))

// Example ping request.
r.GET("/ping", func(c *gin.Context) {
c.String(200, "pong "+fmt.Sprint(time.Now().Unix()))
})

// Listen and Server in 0.0.0.0:8080
r.Run(":8080")
}
49 changes: 49 additions & 0 deletions ginzap/ginzap.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Package ginzap provides log handling using zap package.
// Code structure based on ginrus package.
package ginzap

import (
"time"
"github.com/uber-go/zap"
"github.com/gin-gonic/gin"
)

// Ginzap returns a gin.HandlerFunc (middleware) that logs requests using uber-go/zap.
//
// Requests with errors are logged using zap.Error().
// Requests without errors are logged using zap.Info().
//
// It receives:
// 1. A time package format string (e.g. time.RFC3339).
// 2. A boolean stating whether to use UTC time zone or local.
func Ginzap(logger zap.Logger, timeFormat string, utc bool) gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
// some evil middlewares modify this values
path := c.Request.URL.Path
c.Next()

end := time.Now()
latency := end.Sub(start)
if utc {
end = end.UTC()
}

if len(c.Errors) > 0 {
// Append error field if this is an erroneous request.
for _, e := range c.Errors.Errors() {
logger.Error(e)
}
} else {
logger.Info(path,
zap.Int("status", c.Writer.Status()),
zap.String("method", c.Request.Method),
zap.String("path", path),
zap.String("ip", c.ClientIP()),
zap.Duration("latency", latency),
zap.String("user-agent", c.Request.UserAgent()),
zap.String("time", end.Format(timeFormat)),
)
}
}
}