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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| import ( "go.uber.org/zap" "go.uber.org/zap/zapcore" )
func InitLogger() *zap.Logger { config := zap.Config{ Level: zap.NewAtomicLevelAt(zap.InfoLevel), Development: false, Encoding: "json", EncoderConfig: zapcore.EncoderConfig{ TimeKey: "timestamp", LevelKey: "level", NameKey: "logger", CallerKey: "caller", MessageKey: "message", StacktraceKey: "stacktrace", LineEnding: zapcore.DefaultLineEnding, EncodeLevel: zapcore.LowercaseLevelEncoder, EncodeTime: zapcore.ISO8601TimeEncoder, EncodeDuration: zapcore.SecondsDurationEncoder, EncodeCaller: zapcore.ShortCallerEncoder, }, OutputPaths: []string{"stdout"}, ErrorOutputPaths: []string{"stderr"}, }
logger, _ := config.Build() return logger }
func LoggingMiddleware(logger *zap.Logger) gin.HandlerFunc { return func(c *gin.Context) { start := time.Now() path := c.Request.URL.Path query := c.Request.URL.RawQuery
c.Next()
latency := time.Since(start)
fields := []zap.Field{ zap.Int("status", c.Writer.Status()), zap.String("method", c.Request.Method), zap.String("path", path), zap.String("ip", c.ClientIP()), zap.Duration("latency", latency), zap.String("user_agent", c.Request.UserAgent()), }
if query != "" { fields = append(fields, zap.String("query", sanitizeQuery(query))) }
if requestID := c.GetString("request_id"); requestID != "" { fields = append(fields, zap.String("request_id", requestID)) }
if userID := c.GetUint("user_id"); userID > 0 { fields = append(fields, zap.Uint("user_id", userID)) }
if len(c.Errors) > 0 { fields = append(fields, zap.String("errors", c.Errors.String())) logger.Error("Request failed", fields...) } else { logger.Info("Request completed", fields...) } } }
func sanitizeQuery(query string) string { sensitiveParams := []string{"password", "token", "api_key", "secret"} for _, param := range sensitiveParams { re := regexp.MustCompile(fmt.Sprintf(`(%s=)[^&]*`, param)) query = re.ReplaceAllString(query, "${1}[REDACTED]") } return query }
|
Comments