forked from MartialBE/one-hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
57 lines (49 loc) · 1.41 KB
/
logger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package middleware
import (
"one-api/common/logger"
"one-api/metrics"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/gin-gonic/gin"
)
func SetUpLogger(server *gin.Engine) {
server.Use(GinzapWithConfig())
}
func GinzapWithConfig() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
query := c.Request.URL.RawQuery
c.Next()
end := time.Now()
latency := end.Sub(start)
requestID := c.GetString(logger.RequestIdKey)
userID := c.GetInt("id")
fields := []zapcore.Field{
zap.Int("status", c.Writer.Status()),
zap.String("request_id", requestID),
zap.String("method", c.Request.Method),
zap.String("path", path),
zap.String("query", query),
zap.String("ip", c.ClientIP()),
zap.String("user-agent", c.Request.UserAgent()),
zap.Duration("latency", latency),
zap.Int("user_id", userID),
zap.String("original_model", c.GetString("original_model")),
zap.String("new_model", c.GetString("new_model")),
zap.Int("token_id", c.GetInt("token_id")),
zap.String("token_name", c.GetString("token_name")),
zap.Int("channel_id", c.GetInt("channel_id")),
}
if len(c.Errors) > 0 {
// Append error field if this is an erroneous request.
for _, e := range c.Errors.Errors() {
logger.Logger.Error(e, fields...)
}
} else {
logger.Logger.Info("GIN request", fields...)
}
metrics.RecordHttp(c, latency)
}
}