github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/dm/openapi/logger.go (about) 1 // Copyright 2021 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package openapi 15 16 import ( 17 "fmt" 18 "time" 19 20 "github.com/gin-gonic/gin" 21 "go.uber.org/zap" 22 "go.uber.org/zap/zapcore" 23 ) 24 25 // ZapLogger is a middleware and zap to provide an "access log" like logging for each request. 26 func ZapLogger(log *zap.Logger) gin.HandlerFunc { 27 return func(c *gin.Context) { 28 start := time.Now() 29 c.Next() 30 req := c.Request 31 32 statusCode := c.Writer.Status() 33 fields := []zapcore.Field{ 34 zap.Int("size", c.Writer.Size()), 35 zap.String("host", req.Host), 36 zap.Int("status", statusCode), 37 zap.String("method", req.Method), 38 zap.String("protocol", req.Proto), 39 zap.String("remote_ip", c.Request.RemoteAddr), 40 zap.String("user_agent", req.UserAgent()), 41 zap.String("duration", time.Since(start).String()), 42 zap.String("request", fmt.Sprintf("%s %s", req.Method, req.RequestURI)), 43 } 44 45 switch { 46 case statusCode >= 500: 47 if err := c.Errors.Last(); err != nil { 48 log.With(zap.Error(err)).Error("Server error", fields...) 49 } else { 50 log.Error("Server error", fields...) 51 } 52 case statusCode >= 400: 53 if err := c.Errors.Last(); err != nil { 54 log.With(zap.Error(c.Errors.Last().Err)).Warn("Client error", fields...) 55 } else { 56 log.Warn("Client error", fields...) 57 } 58 case statusCode >= 300: 59 log.Info("Redirection", fields...) 60 default: 61 log.Info("Success", fields...) 62 } 63 } 64 }