generated from xmidt-org/.go-template
-
Notifications
You must be signed in to change notification settings - Fork 5
/
tracer.go
57 lines (49 loc) · 2.18 KB
/
tracer.go
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
// SPDX-FileCopyrightText: 2021 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0
package candlelight
import (
"context"
"net/http"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
)
// LoggerFunc is a strategy for adding key/value pairs (possibly) based on an HTTP request.
// Functions of this type must append key/value pairs to the supplied slice and then return
// the new slice.
type LoggerFunc func([]interface{}, *http.Request) []interface{}
// InjectTraceInfoInLogger adds the traceID and spanID to
// key value pairs that can be provided to a logger.
func InjectTraceInfoInLogger() func([]interface{}, *http.Request) []interface{} {
return func(kvs []interface{}, request *http.Request) []interface{} {
kvs, _ = AppendTraceInfo(request.Context(), kvs)
return kvs
}
}
// AppendTraceInfo appends the trace and span ID key value pairs if they
// are found in the context. The boolean is a quick way to know if the pairs
// were added.
// This should be useful for adding tracing information in logging statements.
func AppendTraceInfo(ctx context.Context, kvs []interface{}) ([]interface{}, bool) {
traceID, spanID, ok := ExtractTraceInfo(ctx)
if !ok {
return kvs, false
}
return append(kvs, SpanIDLogKeyName, spanID, TraceIdLogKeyName, traceID), true
}
// ExtractTraceInfo returns the ID of the trace flowing through the context
// as well as ID the current active span. The third boolean return value represents
// whether the returned IDs are valid and safe to use. OpenTelemetry's noop
// tracer provider, for instance, returns zero value trace information that's
// considered invalid and should be ignored.
func ExtractTraceInfo(ctx context.Context) (string, string, bool) {
span := trace.SpanFromContext(ctx)
traceID := span.SpanContext().TraceID().String()
spanID := span.SpanContext().SpanID().String()
return traceID, spanID, span.SpanContext().IsValid()
}
// InjectTraceInfo will be injecting traceParent and tracestate as
// headers in carrier from span which is available in context.
func InjectTraceInfo(ctx context.Context, carrier propagation.TextMapCarrier) {
prop := propagation.TraceContext{}
prop.Inject(ctx, carrier)
}