/
main.go
65 lines (53 loc) · 1.66 KB
/
main.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
58
59
60
61
62
63
64
65
package main
import (
"bytes"
"fmt"
"io"
"time"
ginzap "github.com/gin-contrib/zap"
"github.com/gin-gonic/gin"
"go.opentelemetry.io/otel/trace"
"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) []zapcore.Field {
fields := []zapcore.Field{}
// log request ID
if requestID := c.Writer.Header().Get("X-Request-Id"); requestID != "" {
fields = append(fields, zap.String("request_id", requestID))
}
// log trace and span ID
if trace.SpanFromContext(c.Request.Context()).SpanContext().IsValid() {
fields = append(fields, zap.String("trace_id", trace.SpanFromContext(c.Request.Context()).SpanContext().TraceID().String()))
fields = append(fields, zap.String("span_id", trace.SpanFromContext(c.Request.Context()).SpanContext().SpanID().String()))
}
// 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 fields
}),
}))
// 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
if err := r.Run(":8080"); err != nil {
panic(err)
}
}