diff --git a/config/config.go b/config/config.go index 84755c8..28ede68 100644 --- a/config/config.go +++ b/config/config.go @@ -32,6 +32,6 @@ func Init() { log.Fatalln("Can't read config!") } if err := viper.Unmarshal(conf); err != nil { - log.Fatal(err) + log.Fatalln(err) } } diff --git a/logger/logrus.go b/logger/logrus.go index 6bf17d0..849aaa8 100644 --- a/logger/logrus.go +++ b/logger/logrus.go @@ -2,7 +2,6 @@ package logger import ( "os" - "time" "github.com/gin-gonic/gin" log "github.com/sirupsen/logrus" @@ -35,26 +34,3 @@ func Init() { gin.SetMode(gin.ReleaseMode) } } - -func Gin() gin.HandlerFunc { - return func(ctx *gin.Context) { - startTime := time.Now() - ctx.Next() - endTime := time.Now() - latencyTime := endTime.Sub(startTime) - reqMethod := ctx.Request.Method - reqUri := ctx.Request.RequestURI - statusCode := ctx.Writer.Status() - clientIP := ctx.ClientIP() - - log.WithFields(log.Fields{ - "METHOD": reqMethod, - "URI": reqUri, - "STATUS": statusCode, - "LATENCY": latencyTime, - "CLIENT_IP": clientIP, - }).Info("HTTP REQUEST") - - ctx.Next() - } -} diff --git a/middleware/gin_logger.go b/middleware/gin_logger.go new file mode 100644 index 0000000..0a3e4ff --- /dev/null +++ b/middleware/gin_logger.go @@ -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") + } + } +} diff --git a/server/server.go b/server/server.go index b036460..6bd8d31 100644 --- a/server/server.go +++ b/server/server.go @@ -2,7 +2,7 @@ package server import ( "net/http" - "nixcn-cms/logger" + "nixcn-cms/middleware" "time" "github.com/gin-gonic/gin" @@ -12,7 +12,7 @@ import ( func Start() { r := gin.Default() - r.Use(logger.Gin(), gin.Recovery()) + r.Use(gin.Recovery(), middleware.GinLogger()) Router(r)