Created
January 26, 2018 13:53
-
-
Save tiagopotencia/077cd93e0c643e0ecafa8511188fd706 to your computer and use it in GitHub Desktop.
HttpLoggerMiddleware
This file contains 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 httplogger | |
import ( | |
"github.com/gin-gonic/gin" | |
"time" | |
"fmt" | |
"log" | |
) | |
func LogRequestInfo(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 | |
raw := c.Request.URL.RawQuery | |
// 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() | |
if raw != "" { | |
path = path + "?" + raw | |
} | |
logSeverity := "Info" | |
if statusCode > 399 { | |
logSeverity = "Error" | |
} | |
log.Println(fmt.Sprintf("%s: %s to: %s | Code: %3d | In: %v | By: %s", | |
logSeverity, | |
method, | |
path, | |
statusCode, | |
latency, | |
clientIP, | |
), nil) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment