• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..19-Jun-2020-

README.mdH A D19-Jun-20201.8 KiB6752

trace.goH A D19-Jun-20209.4 KiB279186

trace_test.goH A D19-Jun-202015 KiB621567

README.md

1# Trace
2
3This package provides an interface for recording the latency of operations and logging details
4about all operations where the latency exceeds a limit.
5
6## Usage
7
8To create a trace:
9
10```go
11func doSomething() {
12    opTrace := trace.New("operation", Field{Key: "fieldKey1", Value: "fieldValue1"})
13    defer opTrace.LogIfLong(100 * time.Millisecond)
14    // do something
15}
16```
17
18To split an trace into multiple steps:
19
20```go
21func 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
31To nest traces:
32
33```go
34func 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
46Traces can also be logged unconditionally or introspected:
47
48```go
49opTrace.TotalTime() // Duration since the Trace was created
50opTrace.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`.
56This is safe even if there is no parent trace already in the context because `(*(Trace)nil).Nest()` returns
57a top level trace.
58
59```go
60func 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```