This repository has been archived by the owner on Jul 7, 2020. It is now read-only.
forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net_context.go
68 lines (58 loc) · 1.42 KB
/
net_context.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
package libkb
import (
"fmt"
"github.com/keybase/client/go/logger"
"golang.org/x/net/context"
"strings"
)
type withLogTagKey string
func WithLogTag(ctx context.Context, k string) context.Context {
ctx = logger.ConvertRPCTagsToLogTags(ctx)
addLogTags := true
tagKey := withLogTagKey(k)
if tags, ok := logger.LogTagsFromContext(ctx); ok {
if _, found := tags[tagKey]; found {
addLogTags = false
}
}
if addLogTags {
newTags := make(logger.CtxLogTags)
newTags[tagKey] = k
ctx = logger.NewContextWithLogTags(ctx, newTags)
}
if _, found := ctx.Value(tagKey).(withLogTagKey); !found {
tag := RandStringB64(3)
ctx = context.WithValue(ctx, tagKey, tag)
}
return ctx
}
func LogTagsToString(ctx context.Context) string {
if ctx == nil {
return ""
}
tags, ok := logger.LogTagsFromContext(ctx)
if !ok || len(tags) == 0 {
return ""
}
var out []string
for key, tag := range tags {
if v := ctx.Value(key); v != nil {
out = append(out, fmt.Sprintf("%s=%s", tag, v))
}
}
return strings.Join(out, ",")
}
func CopyTagsToBackground(ctx context.Context) context.Context {
ret := context.Background()
if tags, ok := logger.LogTagsFromContext(ctx); ok {
ret = logger.NewContextWithLogTags(ret, tags)
for key := range tags {
if ctxKey, ok := key.(withLogTagKey); ok {
if val, ok := ctx.Value(ctxKey).(string); ok && len(val) > 0 {
ret = context.WithValue(ret, ctxKey, val)
}
}
}
}
return ret
}