Files
Message-Push-Nest/middleware/log.go
T

82 lines
1.8 KiB
Go
Raw Normal View History

2024-01-01 12:03:56 +08:00
package middleware
import (
"fmt"
2024-01-02 18:08:52 +08:00
"math"
2024-01-01 12:03:56 +08:00
"message-nest/pkg/logging"
2024-01-02 18:08:52 +08:00
"net/http"
"net/url"
2024-01-01 12:03:56 +08:00
"time"
2024-01-02 18:08:52 +08:00
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
2024-01-01 12:03:56 +08:00
)
2024-01-02 18:08:52 +08:00
// LogMiddleware Logger is the logrus logger handler
func LogMiddleware(notLogged ...string) gin.HandlerFunc {
//hostname, err := os.Hostname()
//if err != nil {
// hostname = "unknown"
//}
2024-01-01 12:03:56 +08:00
2024-01-02 18:08:52 +08:00
var skip map[string]struct{}
if length := len(notLogged); length > 0 {
skip = make(map[string]struct{}, length)
for _, p := range notLogged {
skip[p] = struct{}{}
}
2024-01-01 12:03:56 +08:00
}
return func(c *gin.Context) {
path := c.Request.URL.Path
raw := c.Request.URL.RawQuery
2024-01-02 18:08:52 +08:00
start := time.Now()
2024-01-01 12:03:56 +08:00
c.Next()
2024-01-02 18:08:52 +08:00
stop := time.Since(start)
latency := int(math.Ceil(float64(stop.Nanoseconds()) / 1000000.0))
2024-01-01 12:03:56 +08:00
statusCode := c.Writer.Status()
2024-01-02 18:08:52 +08:00
clientIP := c.ClientIP()
//clientUserAgent := c.Request.UserAgent()
//referer := c.Request.Referer()
dataLength := c.Writer.Size()
if dataLength < 0 {
dataLength = 0
}
2024-01-01 12:03:56 +08:00
if raw != "" {
2024-01-02 18:08:52 +08:00
raw, _ := url.QueryUnescape(raw)
2024-01-01 12:03:56 +08:00
path = path + "?" + raw
}
2024-01-02 18:08:52 +08:00
if _, ok := skip[path]; ok {
return
2024-01-01 12:03:56 +08:00
}
2024-01-02 18:08:52 +08:00
entry := logging.Logger.WithFields(logrus.Fields{
//"hostname": hostname,
"statusCode": statusCode,
2024-01-02 18:10:51 +08:00
"latency": latency,
2024-01-02 18:08:52 +08:00
"clientIP": clientIP,
"method": c.Request.Method,
"path": path,
//"referer": referer,
"dataLength": dataLength,
//"userAgent": clientUserAgent,
})
2024-01-01 12:03:56 +08:00
2024-01-02 18:08:52 +08:00
if len(c.Errors) > 0 {
entry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String())
} else {
msg := fmt.Sprintf("[Gin] %s [%s] %s %d %d (%dms)", clientIP, c.Request.Method, path, statusCode, dataLength, latency)
if statusCode >= http.StatusInternalServerError {
entry.Error(msg)
} else if statusCode >= http.StatusBadRequest {
entry.Warn(msg)
} else {
entry.Info(msg)
}
}
2024-01-01 12:03:56 +08:00
}
}