mirror of https://github.com/toorop/gin-logrus.git
First commit
This commit is contained in:
parent
caa96d4b50
commit
584f90a544
24
README.md
24
README.md
|
@ -1,2 +1,24 @@
|
|||
# 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")
|
||||
```
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue