50 lines
1.0 KiB
Go
50 lines
1.0 KiB
Go
package middleware
|
|
|
|
import (
|
|
"bytes"
|
|
"io"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/sirupsen/logrus"
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
func GinLogger() 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")
|
|
}
|
|
}
|
|
}
|