Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 517105f

Browse files
gcp: Surface trace propagation functions on context (#40)
Users of clog have to be able to reliably put trace information into the context to make the logger pick it up correctly. The current implementation uses a string, which is prone to collisions. This surfaces context manipulation functions instead that operate on a private type and allow for easier integration.
1 parent b5e6d19 commit 517105f

3 files changed

Lines changed: 18 additions & 13 deletions

File tree

gcp/setup.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ func (h *Handler) Enabled(ctx context.Context, level slog.Level) bool {
4141
}
4242

4343
func (h *Handler) Handle(ctx context.Context, rec slog.Record) error {
44-
if trace := traceFromContext(ctx); trace != "" {
44+
if trace := TraceFromContext(ctx); trace != "" {
4545
rec = rec.Clone()
4646
// Add trace ID to the record so it is correlated with the request log
4747
// See https://cloud.google.com/trace/docs/trace-log-integration

gcp/trace.go

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,14 +101,25 @@ func WithCloudTraceContext(h http.Handler) http.Handler {
101101
if traceID != "" {
102102
trace = fmt.Sprintf("projects/%s/traces/%s", projectID, traceID)
103103
}
104-
r = r.WithContext(context.WithValue(r.Context(), "trace", trace))
104+
r = r.WithContext(WithTrace(r.Context(), trace))
105105
}
106106
h.ServeHTTP(w, r)
107107
})
108108
}
109109

110-
func traceFromContext(ctx context.Context) string {
111-
trace := ctx.Value("trace")
110+
type traceKey struct{}
111+
112+
// WithTrace adds a trace information to the context.
113+
func WithTrace(ctx context.Context, trace string) context.Context {
114+
if trace == "" {
115+
return ctx
116+
}
117+
return context.WithValue(ctx, traceKey{}, trace)
118+
}
119+
120+
// TraceFromContext retrieves the trace information from the context.
121+
func TraceFromContext(ctx context.Context) string {
122+
trace := ctx.Value(traceKey{})
112123
if trace == nil {
113124
return ""
114125
}

gcp/trace_test.go

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,15 +42,9 @@ func TestTrace(t *testing.T) {
4242
t.Error("got empty trace context header, want non-empty")
4343
}
4444

45-
traceCtx := ctx.Value("trace")
46-
if traceCtx == nil {
47-
if c.wantTrace != "" {
48-
t.Fatalf("want %s, not found", c.wantTrace)
49-
}
50-
} else {
51-
if traceCtx != c.wantTrace {
52-
t.Fatalf("got %s, want %s", traceCtx, c.wantTrace)
53-
}
45+
traceCtx := TraceFromContext(ctx)
46+
if traceCtx != c.wantTrace {
47+
t.Fatalf("got %s, want %s", traceCtx, c.wantTrace)
5448
}
5549
}))
5650
srv := httptest.NewServer(h)

0 commit comments

Comments
 (0)