Last active
January 30, 2022 15:31
-
-
Save fclairamb/c5b001024bbfb265a046e788ce1cde74 to your computer and use it in GitHub Desktop.
GIN Logger with go-kit/log
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 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