Skip to content

Instantly share code, notes, and snippets.

@fclairamb
Last active January 30, 2022 15:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fclairamb/c5b001024bbfb265a046e788ce1cde74 to your computer and use it in GitHub Desktop.
Save fclairamb/c5b001024bbfb265a046e788ce1cde74 to your computer and use it in GitHub Desktop.
GIN Logger with go-kit/log
package ginlogger
// Directly inspired from the default gin.Logger
// This is to be used like this:
// r := gin.New()
// r.Use(gin.Recovery())
// r.Use(ginlogger.LoggerWithGoKit(mylogger))
import (
"time"
"github.com/gin-gonic/gin"
"github.com/go-kit/kit/log"
)
func LoggerWithGoKit(logger log.Logger, notlogged ...string) gin.HandlerFunc {
var skip map[string]struct{}
if length := len(notlogged); length > 0 {
skip = make(map[string]struct{}, length)
for _, path := range notlogged {
skip[path] = struct{}{}
}
}
return func(c *gin.Context) {
// Start timer
start := time.Now()
path := c.Request.URL.Path
// Process request
c.Next()
// Log only when path is not being skipped
if _, ok := skip[path]; !ok {
// Stop timer
end := time.Now()
latency := end.Sub(start)
clientIP := c.ClientIP()
method := c.Request.Method
statusCode := c.Writer.Status()
logger.Log(
"action", "api.http_request",
"path", path,
"method", method,
"statusCode", statusCode,
"latency", latency,
"clientIp", clientIP,
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment