diff --git a/README.md b/README.md index 241c53f..b36d5da 100644 --- a/README.md +++ b/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") +``` \ No newline at end of file diff --git a/logger.go b/logger.go new file mode 100644 index 0000000..2cde142 --- /dev/null +++ b/logger.go @@ -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) + } + } + } +}