Add option to skip logging specified endpoints

This commit is contained in:
Roman Zaynetdinov 2015-07-22 17:02:36 +03:00
parent fd5d4294a5
commit f13c3ae898
2 changed files with 46 additions and 19 deletions

View File

@ -46,7 +46,17 @@ func Logger() HandlerFunc {
// Instance a Logger middleware with the specified writter buffer. // Instance a Logger middleware with the specified writter buffer.
// Example: os.Stdout, a file opened in write mode, a socket... // Example: os.Stdout, a file opened in write mode, a socket...
func LoggerWithWriter(out io.Writer) HandlerFunc { func LoggerWithWriter(out io.Writer, notlogged ...string) 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 *Context) { return func(c *Context) {
// Start timer // Start timer
start := time.Now() start := time.Now()
@ -55,26 +65,29 @@ func LoggerWithWriter(out io.Writer) HandlerFunc {
// Process request // Process request
c.Next() c.Next()
// Stop timer // Log only when path is not being skipped
end := time.Now() if _, ok := skip[path]; !ok {
latency := end.Sub(start) // Stop timer
end := time.Now()
latency := end.Sub(start)
clientIP := c.ClientIP() clientIP := c.ClientIP()
method := c.Request.Method method := c.Request.Method
statusCode := c.Writer.Status() statusCode := c.Writer.Status()
statusColor := colorForStatus(statusCode) statusColor := colorForStatus(statusCode)
methodColor := colorForMethod(method) methodColor := colorForMethod(method)
comment := c.Errors.ByType(ErrorTypePrivate).String() comment := c.Errors.ByType(ErrorTypePrivate).String()
fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %s |%s %s %-7s %s\n%s", fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %s |%s %s %-7s %s\n%s",
end.Format("2006/01/02 - 15:04:05"), end.Format("2006/01/02 - 15:04:05"),
statusColor, statusCode, reset, statusColor, statusCode, reset,
latency, latency,
clientIP, clientIP,
methodColor, reset, method, methodColor, reset, method,
path, path,
comment, comment,
) )
}
} }
} }

View File

@ -124,3 +124,17 @@ func TestErrorLogger(t *testing.T) {
assert.Equal(t, w.Code, 500) assert.Equal(t, w.Code, 500)
assert.Equal(t, w.Body.String(), "hola!") assert.Equal(t, w.Body.String(), "hola!")
} }
func TestSkippingPaths(t *testing.T) {
buffer := new(bytes.Buffer)
router := New()
router.Use(LoggerWithWriter(buffer, "/skipped"))
router.GET("/logged", func(c *Context) {})
router.GET("/skipped", func(c *Context) {})
performRequest(router, "GET", "/logged")
assert.Contains(t, buffer.String(), "200")
performRequest(router, "GET", "/skipped")
assert.Contains(t, buffer.String(), "")
}