48
middleware/gin_logger.go
Normal file
48
middleware/gin_logger.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func GinLogger(log *logrus.Logger) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var body []byte
|
||||
if c.Request.Body != nil {
|
||||
body, _ = io.ReadAll(c.Request.Body)
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
}
|
||||
|
||||
startTime := time.Now()
|
||||
|
||||
c.Next()
|
||||
|
||||
var errorMessage string
|
||||
if len(c.Errors) > 0 {
|
||||
errorMessage = c.Errors.String()
|
||||
}
|
||||
|
||||
entry := log.WithFields(logrus.Fields{
|
||||
"status": c.Writer.Status(),
|
||||
"method": c.Request.Method,
|
||||
"uri": c.Request.RequestURI,
|
||||
"ip": c.ClientIP(),
|
||||
"latency": time.Since(startTime).String(),
|
||||
"user_agent": c.Request.UserAgent(),
|
||||
"request_body": string(body),
|
||||
"errors": errorMessage,
|
||||
})
|
||||
|
||||
if len(c.Errors) > 0 || c.Writer.Status() >= 500 {
|
||||
entry.Error("HTTP_ERROR")
|
||||
} else if c.Writer.Status() >= 400 {
|
||||
entry.Warn("HTTP_CLIENT_ERROR")
|
||||
} else {
|
||||
entry.Info("HTTP_SUCCESS")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user