MCPcopy Create free account
hub / github.com/GoSimplicity/LinkMe / Log

Method Log

middleware/log.go:32–61  ·  view source on GitHub ↗

Log 日志中间件

()

Source from the content-addressed store, hash-verified

30
31// Log 日志中间件
32func (lm *LogMiddleware) Log() gin.HandlerFunc {
33 return func(c *gin.Context) {
34 // 开始时间
35 start := time.Now()
36 // 请求路径
37 path := c.Request.URL.Path
38 // 请求方法
39 method := c.Request.Method
40 // 读取请求体
41 bodyBytes, err := ioutil.ReadAll(c.Request.Body)
42 if err != nil {
43 lm.l.Error("请求体读取失败", zap.Error(err))
44 c.AbortWithStatus(http.StatusInternalServerError)
45 return
46 }
47 // 由于读取请求体会消耗掉c.Request.Body,所以需要重新设置回上下文
48 c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
49 al := AccessLog{
50 Path: path,
51 Method: method,
52 ReqBody: string(bodyBytes),
53 }
54 c.Next()
55 // 记录响应状态码和响应体
56 al.Status = c.Writer.Status()
57 al.RespBody = c.Writer.Header().Get("Content-Type")
58 al.Duration = time.Since(start)
59 lm.l.Info("请求日志", zap.Any("accessLog", al))
60 }
61}

Callers 1

InitMiddlewaresFunction · 0.80

Calls 1

GetMethod · 0.65

Tested by

no test coverage detected