First commit

This commit is contained in:
Stéphane Depierrepont aka Toorop 2016-09-26 16:22:16 +02:00
parent caa96d4b50
commit 584f90a544
2 changed files with 69 additions and 1 deletions

View File

@ -1,2 +1,24 @@
# gin-logrus # gin-logrus
gin middleware for logrus
[Logrus](https://github.com/Sirupsen/logrus) logger middleware for [Gin](https://gin-gonic.github.io/gin/)
![golang gin middleware logrus logger](http://i.imgur.com/P140Vi0.png)
## Usage
```go
import (
"github.com/Sirupsen/logrus"
"github.com/toorop/gin-logrus"
"github.com/gin-gonic/gin"
log := logrus.New()
r := gin.New()
r.Use(ginlogrus.Logger(log), gin.Recovery())
// pingpong
r.GET("/ping", func(c *gin.Context) {
c.Data(200, "text/plain", []byte("pong"))
})
r.Run("127.0.0.1:8080")
```

46
logger.go Normal file
View File

@ -0,0 +1,46 @@
package ginlogrus
import (
"fmt"
"math"
"time"
"github.com/Sirupsen/logrus"
"github.com/gin-gonic/gin"
)
// Logger is the logrus logger handler
func Logger(log *logrus.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
// other handler can change c.Path so:
path := c.Request.URL.Path
start := time.Now()
c.Next()
stop := time.Since(start)
statusCode := c.Writer.Status()
latency := int(math.Ceil(float64(stop.Nanoseconds()) / 1000.0))
clientIP := c.ClientIP()
entry := logrus.NewEntry(log).WithFields(logrus.Fields{
"statusCode": statusCode,
"latency": latency, // time to process
"clientIP": clientIP,
"method": c.Request.Method,
"path": path,
})
if len(c.Errors) > 0 {
entry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String())
} else {
msg := fmt.Sprintf("%s - %s %s %d (%dms)", clientIP, c.Request.Method, path, statusCode, latency)
if statusCode > 499 {
entry.Error(msg)
} else if statusCode > 399 {
entry.Warn(msg)
} else {
entry.Info(msg)
}
}
}
}