diff --git a/README.md b/README.md index 7a4d169..51913b8 100644 --- a/README.md +++ b/README.md @@ -118,3 +118,50 @@ This will add the `traceId` field to log: "traceID": "285f31ec1dba4b79034c4415ad18e4ed" } ``` + +## Custom Zap fields + +example for custom log request body and response request ID + +```go +func main() { + r := gin.New() + + logger, _ := zap.NewProduction() + + r.Use(ginzap.GinzapWithConfig(logger, &ginzap.Config{ + UTC: true, + TimeFormat: time.RFC3339, + Context: ginzap.Fn(func(c *gin.Context) (fields []zapcore.Field) { + // log response ID + if requestID := c.Writer.Header().Get("X-Request-Id"); requestID != "" { + fields = append(fields, zap.String("request-id", requestID)) + } + + // log request body + var body []byte + var buf bytes.Buffer + tee := io.TeeReader(c.Request.Body, &buf) + body, _ = io.ReadAll(tee) + c.Request.Body = io.NopCloser(&buf) + fields = append(fields, zap.String("body", string(body))) + + return + }), + })) + + // Example ping request. + r.GET("/ping", func(c *gin.Context) { + c.Writer.Header().Add("X-Request-Id", "1234-5678-9012") + c.String(200, "pong "+fmt.Sprint(time.Now().Unix())) + }) + + r.POST("/ping", func(c *gin.Context) { + c.Writer.Header().Add("X-Request-Id", "9012-5678-1234") + c.String(200, "pong "+fmt.Sprint(time.Now().Unix())) + }) + + // Listen and Server in 0.0.0.0:8080 + r.Run(":8080") +} +``` diff --git a/_example/main.go b/_example/example01/main.go similarity index 100% rename from _example/main.go rename to _example/example01/main.go diff --git a/_example/example02/main.go b/_example/example02/main.go new file mode 100644 index 0000000..ceda28e --- /dev/null +++ b/_example/example02/main.go @@ -0,0 +1,54 @@ +package main + +import ( + "bytes" + "fmt" + "io" + "time" + + ginzap "github.com/gin-contrib/zap" + "github.com/gin-gonic/gin" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" +) + +func main() { + r := gin.New() + + logger, _ := zap.NewProduction() + + r.Use(ginzap.GinzapWithConfig(logger, &ginzap.Config{ + UTC: true, + TimeFormat: time.RFC3339, + Context: ginzap.Fn(func(c *gin.Context) (fields []zapcore.Field) { + // log response ID + if requestID := c.Writer.Header().Get("X-Request-Id"); requestID != "" { + fields = append(fields, zap.String("request-id", requestID)) + } + + // log request body + var body []byte + var buf bytes.Buffer + tee := io.TeeReader(c.Request.Body, &buf) + body, _ = io.ReadAll(tee) + c.Request.Body = io.NopCloser(&buf) + fields = append(fields, zap.String("body", string(body))) + + return + }), + })) + + // Example ping request. + r.GET("/ping", func(c *gin.Context) { + c.Writer.Header().Add("X-Request-Id", "1234-5678-9012") + c.String(200, "pong "+fmt.Sprint(time.Now().Unix())) + }) + + r.POST("/ping", func(c *gin.Context) { + c.Writer.Header().Add("X-Request-Id", "9012-5678-1234") + c.String(200, "pong "+fmt.Sprint(time.Now().Unix())) + }) + + // Listen and Server in 0.0.0.0:8080 + r.Run(":8080") +}