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

127 lines
2.8 KiB
Go
Raw Normal View History

2024-01-01 12:03:56 +08:00
package middleware
import (
2025-12-06 21:11:15 +08:00
"bytes"
2024-01-01 12:03:56 +08:00
"fmt"
2024-01-02 18:08:52 +08:00
"math"
2025-12-06 21:11:15 +08:00
"strings"
2024-01-13 12:04:40 +08:00
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
)
2025-12-06 21:11:15 +08:00
// 需要记录响应内容的 API 路径前缀
var logResponsePaths = []string{
"/api/v1/message/send",
"/api/v2/message/send",
}
// responseBodyWriter 用于捕获响应内容
type responseBodyWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (w responseBodyWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
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
2025-12-06 21:11:15 +08:00
// 判断是否需要捕获响应内容
needCaptureResponse := false
for _, logPath := range logResponsePaths {
if strings.HasPrefix(path, logPath) {
needCaptureResponse = true
break
}
}
var bodyWriter *responseBodyWriter
if needCaptureResponse {
bodyWriter = &responseBodyWriter{
ResponseWriter: c.Writer,
body: bytes.NewBufferString(""),
}
c.Writer = bodyWriter
}
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-13 12:04:40 +08:00
entry := logrus.WithFields(logrus.Fields{
2024-01-13 11:43:54 +08:00
////"hostname": hostname,
//"statusCode": statusCode,
//"latency": latency,
//"clientIP": clientIP,
//"method": c.Request.Method,
//"path": path,
////"referer": referer,
//"dataLength": dataLength,
////"userAgent": clientUserAgent,
"prefix": "[Gin]",
2024-01-02 18:08:52 +08:00
})
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 {
2024-01-13 11:43:54 +08:00
msg := fmt.Sprintf("%s [%s] %s %d %d (%dms)", clientIP, c.Request.Method, path, statusCode, dataLength, latency)
2025-12-06 21:11:15 +08:00
// 如果是发送消息的 API,打印返回内容
if needCaptureResponse && bodyWriter != nil {
responseBody := bodyWriter.body.String()
msg = fmt.Sprintf("%s | Response: %s", msg, responseBody)
}
2024-01-02 18:08:52 +08:00
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
}
}