...
1 package middleware
2
3 import (
4 "context"
5
6 "edge-infra.dev/pkg/lib/fog"
7
8 "github.com/gin-contrib/requestid"
9 "github.com/gin-gonic/gin"
10 "github.com/go-logr/logr"
11 )
12
13 type correlationIDKey struct{}
14
15 const (
16 CorrelationIDKey = "X-Correlation-ID"
17 correlationIDLabel = "correlationID"
18 )
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35 func SetLoggerInContext(log logr.Logger) gin.HandlerFunc {
36 return func(c *gin.Context) {
37 correlationID := requestid.Get(c)
38 operationID := fog.OperationID(c.Request.Context())
39
40 log := log.WithValues(correlationIDLabel, correlationID)
41 log = log.WithValues(fog.OperationFields(operationID)...)
42
43 ctxWithID := context.WithValue(c.Request.Context(), correlationIDKey{}, correlationID)
44 c.Request = c.Request.Clone(fog.IntoContext(ctxWithID, log))
45
46 c.Next()
47 }
48 }
49
50
51
52 func RequestBookendLogs() gin.HandlerFunc {
53 return func(c *gin.Context) {
54
55 url := c.Request.URL.Path
56 log := fog.FromContext(c, "endpoint", url)
57 c.Request = c.Request.Clone(fog.IntoContext(c.Request.Context(), log))
58 log.Info("Request received")
59
60 c.Next()
61
62
63 status := c.Writer.Status()
64 log = fog.FromContext(c, "statusCode", status)
65 if status < 400 {
66 log = log.WithValues("isSuccessful", true)
67 } else {
68 log = log.WithValues("isSuccessful", false)
69 }
70 log.Info("Request completed")
71 }
72 }
73
74 func GetCorrelationID(ctx context.Context) string {
75 correlationID := ctx.Value(correlationIDKey{})
76 if correlationID == nil {
77 return ""
78 }
79 return correlationID.(string)
80 }
81
View as plain text