mirror of https://github.com/toorop/gin-logrus.git
Merge pull request #7 from Hermsi1337/#6/skip-paths-in-log
optionally skip paths to log
This commit is contained in:
commit
d2ee50d38d
22
logger.go
22
logger.go
|
@ -3,6 +3,7 @@ package ginlogrus
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
@ -19,11 +20,22 @@ import (
|
||||||
var timeFormat = "02/Jan/2006:15:04:05 -0700"
|
var timeFormat = "02/Jan/2006:15:04:05 -0700"
|
||||||
|
|
||||||
// Logger is the logrus logger handler
|
// Logger is the logrus logger handler
|
||||||
func Logger(logger logrus.FieldLogger) gin.HandlerFunc {
|
func Logger(logger logrus.FieldLogger, notLogged ...string) gin.HandlerFunc {
|
||||||
hostname, err := os.Hostname()
|
hostname, err := os.Hostname()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
hostname = "unknow"
|
hostname = "unknow"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var skip map[string]struct{}
|
||||||
|
|
||||||
|
if length := len(notLogged); length > 0 {
|
||||||
|
skip = make(map[string]struct{}, length)
|
||||||
|
|
||||||
|
for _, p := range notLogged {
|
||||||
|
skip[p] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
// other handler can change c.Path so:
|
// other handler can change c.Path so:
|
||||||
path := c.Request.URL.Path
|
path := c.Request.URL.Path
|
||||||
|
@ -40,6 +52,10 @@ func Logger(logger logrus.FieldLogger) gin.HandlerFunc {
|
||||||
dataLength = 0
|
dataLength = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if _, ok := skip[path]; ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
entry := logger.WithFields(logrus.Fields{
|
entry := logger.WithFields(logrus.Fields{
|
||||||
"hostname": hostname,
|
"hostname": hostname,
|
||||||
"statusCode": statusCode,
|
"statusCode": statusCode,
|
||||||
|
@ -56,9 +72,9 @@ func Logger(logger logrus.FieldLogger) gin.HandlerFunc {
|
||||||
entry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String())
|
entry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String())
|
||||||
} else {
|
} else {
|
||||||
msg := fmt.Sprintf("%s - %s [%s] \"%s %s\" %d %d \"%s\" \"%s\" (%dms)", clientIP, hostname, time.Now().Format(timeFormat), c.Request.Method, path, statusCode, dataLength, referer, clientUserAgent, latency)
|
msg := fmt.Sprintf("%s - %s [%s] \"%s %s\" %d %d \"%s\" \"%s\" (%dms)", clientIP, hostname, time.Now().Format(timeFormat), c.Request.Method, path, statusCode, dataLength, referer, clientUserAgent, latency)
|
||||||
if statusCode > 499 {
|
if statusCode >= http.StatusInternalServerError {
|
||||||
entry.Error(msg)
|
entry.Error(msg)
|
||||||
} else if statusCode > 399 {
|
} else if statusCode >= http.StatusBadRequest {
|
||||||
entry.Warn(msg)
|
entry.Warn(msg)
|
||||||
} else {
|
} else {
|
||||||
entry.Info(msg)
|
entry.Info(msg)
|
||||||
|
|
Loading…
Reference in New Issue