File: README.md

package info (click to toggle)
golang-k8s-utils 0.0~git20250321.1f6e0b7-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 1,012 kB
  • sloc: sh: 245; makefile: 27
file content (67 lines) | stat: -rw-r--r-- 1,848 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# Trace

This package provides an interface for recording the latency of operations and logging details
about all operations where the latency exceeds a limit.

## Usage

To create a trace:

```go
func doSomething() {
    opTrace := trace.New("operation", Field{Key: "fieldKey1", Value: "fieldValue1"})
    defer opTrace.LogIfLong(100 * time.Millisecond)
    // do something
}
```

To split an trace into multiple steps:

```go
func doSomething() {
    opTrace := trace.New("operation")
    defer opTrace.LogIfLong(100 * time.Millisecond)
    // do step 1
    opTrace.Step("step1", Field{Key: "stepFieldKey1", Value: "stepFieldValue1"})
    // do step 2
    opTrace.Step("step2")
}
```

To nest traces:

```go
func doSomething() {
    rootTrace := trace.New("rootOperation")
    defer rootTrace.LogIfLong(100 * time.Millisecond)
    
    func() {
        nestedTrace := rootTrace.Nest("nested", Field{Key: "nestedFieldKey1", Value: "nestedFieldValue1"})
        defer nestedTrace.LogIfLong(50 * time.Millisecond)
        // do nested operation
    }()
}
```

Traces can also be logged unconditionally or introspected:

```go
opTrace.TotalTime() // Duration since the Trace was created
opTrace.Log() // unconditionally log the trace
```

### Using context.Context to nest traces

`context.Context` can be used to manage nested traces. Create traces by calling `trace.GetTraceFromContext(ctx).Nest`. 
This is safe even if there is no parent trace already in the context because `(*(Trace)nil).Nest()` returns
a top level trace.

```go
func doSomething(ctx context.Context) {
    opTrace := trace.FromContext(ctx).Nest("operation") // create a trace, possibly nested
    ctx = trace.ContextWithTrace(ctx, opTrace) // make this trace the parent trace of the context
    defer opTrace.LogIfLong(50 * time.Millisecond)
    
    doSomethingElse(ctx)
}
```