Name | Date | Size | #Lines | LOC | ||
---|---|---|---|---|---|---|
.. | 19-Jun-2020 | - | ||||
README.md | H A D | 19-Jun-2020 | 1.8 KiB | 67 | 52 | |
trace.go | H A D | 19-Jun-2020 | 9.4 KiB | 279 | 186 | |
trace_test.go | H A D | 19-Jun-2020 | 15 KiB | 621 | 567 |
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```