forked from cortexproject/cortex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrappers.go
91 lines (77 loc) · 2.52 KB
/
wrappers.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package log
import (
"context"
"github.com/go-kit/log"
"github.com/opentracing/opentracing-go"
"github.com/uber/jaeger-client-go"
"go.opentelemetry.io/otel/trace"
"github.com/cortexproject/cortex/pkg/tenant"
)
// WithUserID returns a Logger that has information about the current user in
// its details.
func WithUserID(userID string, l log.Logger) log.Logger {
// See note in WithContext.
return log.With(l, "org_id", userID)
}
// WithTraceID returns a Logger that has information about the traceID in
// its details.
func WithTraceID(traceID string, l log.Logger) log.Logger {
// See note in WithContext.
return log.With(l, "traceID", traceID)
}
// WithExecutionID returns a Logger that has information about the execution id in
// its details.
func WithExecutionID(executionID string, l log.Logger) log.Logger {
return log.With(l, "execution_id", executionID)
}
// WithContext returns a Logger that has information about the current user in
// its details.
//
// e.g.
//
// log := util.WithContext(ctx)
// log.Errorf("Could not chunk chunks: %v", err)
func WithContext(ctx context.Context, l log.Logger) log.Logger {
l = HeadersFromContext(ctx, l)
// Weaveworks uses "orgs" and "orgID" to represent Cortex users,
// even though the code-base generally uses `userID` to refer to the same thing.
userID, err := tenant.TenantID(ctx)
if err == nil {
l = WithUserID(userID, l)
}
traceID, ok := ExtractSampledTraceID(ctx)
if !ok {
return l
}
return WithTraceID(traceID, l)
}
// WithSourceIPs returns a Logger that has information about the source IPs in
// its details.
func WithSourceIPs(sourceIPs string, l log.Logger) log.Logger {
return log.With(l, "sourceIPs", sourceIPs)
}
// HeadersFromContext enables the logging of specified HTTP Headers that have been added to a context
func HeadersFromContext(ctx context.Context, l log.Logger) log.Logger {
headerContentsMap := HeaderMapFromContext(ctx)
for header, contents := range headerContentsMap {
l = log.With(l, header, contents)
}
return l
}
// ExtractSampledTraceID gets traceID and whether the trace is samples or not.
func ExtractSampledTraceID(ctx context.Context) (string, bool) {
sp := opentracing.SpanFromContext(ctx)
if sp == nil {
return "", false
}
sctx, ok := sp.Context().(jaeger.SpanContext)
if !ok {
// If OpenTracing span not found, try OTEL.
span := trace.SpanFromContext(ctx)
if span != nil {
return span.SpanContext().TraceID().String(), span.SpanContext().IsSampled()
}
return "", false
}
return sctx.TraceID().String(), sctx.IsSampled()
}