From f13c3ae89848df0f5b72240b986f759280decc8b Mon Sep 17 00:00:00 2001 From: Roman Zaynetdinov Date: Wed, 22 Jul 2015 17:02:36 +0300 Subject: [PATCH] Add option to skip logging specified endpoints --- logger.go | 51 +++++++++++++++++++++++++++++++------------------- logger_test.go | 14 ++++++++++++++ 2 files changed, 46 insertions(+), 19 deletions(-) diff --git a/logger.go b/logger.go index e0f9b367..c5d4c3e2 100644 --- a/logger.go +++ b/logger.go @@ -46,7 +46,17 @@ func Logger() HandlerFunc { // Instance a Logger middleware with the specified writter buffer. // 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) { // Start timer start := time.Now() @@ -55,26 +65,29 @@ func LoggerWithWriter(out io.Writer) HandlerFunc { // Process request c.Next() - // Stop timer - end := time.Now() - latency := end.Sub(start) + // 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() - statusColor := colorForStatus(statusCode) - methodColor := colorForMethod(method) - comment := c.Errors.ByType(ErrorTypePrivate).String() + clientIP := c.ClientIP() + method := c.Request.Method + statusCode := c.Writer.Status() + statusColor := colorForStatus(statusCode) + methodColor := colorForMethod(method) + comment := c.Errors.ByType(ErrorTypePrivate).String() - fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %s |%s %s %-7s %s\n%s", - end.Format("2006/01/02 - 15:04:05"), - statusColor, statusCode, reset, - latency, - clientIP, - methodColor, reset, method, - path, - comment, - ) + fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %s |%s %s %-7s %s\n%s", + end.Format("2006/01/02 - 15:04:05"), + statusColor, statusCode, reset, + latency, + clientIP, + methodColor, reset, method, + path, + comment, + ) + } } } diff --git a/logger_test.go b/logger_test.go index 267f9c5b..dc6ba64b 100644 --- a/logger_test.go +++ b/logger_test.go @@ -124,3 +124,17 @@ func TestErrorLogger(t *testing.T) { assert.Equal(t, w.Code, 500) 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(), "") +}