Debian Codegraph @

trace/README.md

raw
1 # Trace
2
3 This package provides an interface for recording the latency of operations and logging details
4 about all operations where the latency exceeds a limit.
5
6 ## Usage
7
8 To create a trace:
9
10 ```go
11 func doSomething() {
12 opTrace := trace.New("operation", Field{Key: "fieldKey1", Value: "fieldValue1"})
13 defer opTrace.LogIfLong(100 * time.Millisecond)
14 // do something
15 }
16 ```
17
18 To split an trace into multiple steps:
19
20 ```go
21 func doSomething() {
22 opTrace := trace.New("operation")
23 defer opTrace.LogIfLong(100 * time.Millisecond)
24 // do step 1
25 opTrace.Step("step1", Field{Key: "stepFieldKey1", Value: "stepFieldValue1"})
26 // do step 2
27 opTrace.Step("step2")
28 }
29 ```
30
31 To nest traces:
32
33 ```go
34 func doSomething() {
35 rootTrace := trace.New("rootOperation")
36 defer rootTrace.LogIfLong(100 * time.Millisecond)
37
38 func() {
39 nestedTrace := rootTrace.Nest("nested", Field{Key: "nestedFieldKey1", Value: "nestedFieldValue1"})
40 defer nestedTrace.LogIfLong(50 * time.Millisecond)
41 // do nested operation
42 }()
43 }
44 ```
45
46 Traces can also be logged unconditionally or introspected:
47
48 ```go
49 opTrace.TotalTime() // Duration since the Trace was created
50 opTrace.Log() // unconditionally log the trace
51 ```
52
53 ### Using context.Context to nest traces
54
55 `context.Context` can be used to manage nested traces. Create traces by calling `trace.GetTraceFromContext(ctx).Nest`.
56 This is safe even if there is no parent trace already in the context because `(*(Trace)nil).Nest()` returns
57 a top level trace.
58
59 ```go
60 func doSomething(ctx context.Context) {
61 opTrace := trace.FromContext(ctx).Nest("operation") // create a trace, possibly nested
62 ctx = trace.ContextWithTrace(ctx, opTrace) // make this trace the parent trace of the context
63 defer opTrace.LogIfLong(50 * time.Millisecond)
64
65 doSomethingElse(ctx)
66 }
67 ```