7 "github.com/docker/distribution/uuid"
10 // WithTrace allocates a traced timing span in a new context. This allows a
11 // caller to track the time between calling WithTrace and the returned done
12 // function. When the done function is called, a log message is emitted with a
13 // "trace.duration" field, corresponding to the elapsed time and a
14 // "trace.func" field, corresponding to the function that called WithTrace.
16 // The logging keys "trace.id" and "trace.parent.id" are provided to implement
17 // dapper-like tracing. This function should be complemented with a WithSpan
18 // method that could be used for tracing distributed RPC calls.
20 // The main benefit of this function is to post-process log messages or
21 // intercept them in a hook to provide timing data. Trace ids and parent ids
22 // can also be linked to provide call tracing, if so required.
24 // Here is an example of the usage:
26 // func timedOperation(ctx Context) {
27 // ctx, done := WithTrace(ctx)
28 // defer done("this will be the log message")
29 // // ... function body ...
32 // If the function ran for roughly 1s, such a usage would emit a log message
35 // INFO[0001] this will be the log message trace.duration=1.004575763s trace.func=github.com/docker/distribution/context.traceOperation trace.id=<id> ...
37 // Notice that the function name is automatically resolved, along with the
38 // package and a trace id is emitted that can be linked with parent ids.
39 func WithTrace(ctx Context) (Context, func(format string, a ...interface{})) {
44 pc, file, line, _ := runtime.Caller(1)
45 f := runtime.FuncForPC(pc)
48 id: uuid.Generate().String(),
50 parent: GetStringValue(ctx, "trace.id"),
56 return ctx, func(format string, a ...interface{}) {
68 // traced represents a context that is traced for function call timing. It
69 // also provides fast lookup for the various attributes that are available on
81 func (ts *traced) Value(key interface{}) interface{} {
85 case "trace.duration":
86 return time.Since(ts.start)
89 case "trace.parent.id":
91 return nil // must return nil to signal no parent.
103 return ts.Context.Value(key)