-
Notifications
You must be signed in to change notification settings - Fork 3
/
context.go
70 lines (61 loc) · 1.82 KB
/
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
69
70
package ulog
import "golang.org/x/net/context"
type (
fieldsKeyType struct{}
adapterKeyType struct{}
callDepthKeyType struct{}
fieldKey string
)
var (
fieldsKey fieldsKeyType
adapterKey adapterKeyType
callDepthKey callDepthKeyType
)
// withField creates a context that holds key-value pair to log.
func withField(ctx context.Context, key string, value interface{}) context.Context {
fk := fieldKey(key)
ctx = context.WithValue(ctx, fk, value)
fks, _ := ctx.Value(fieldsKey).([]fieldKey)
for _, fk := range fks {
if string(fk) == key {
// fields already contains key
return ctx
}
}
ctx = context.WithValue(ctx, fieldsKey, append(fks, fk))
return ctx
}
func fieldsFromContext(ctx context.Context) []Field {
keys, _ := ctx.Value(fieldsKey).([]fieldKey)
if len(keys) == 0 {
return nil
}
fs := make([]Field, len(keys))
for i := range keys {
fs[i] = Field{
Key: string(keys[i]),
Value: ctx.Value(keys[i]),
}
}
return fs
}
// withAdapter returns a new context that holds LoggerAdapter that is used to logging.
func withAdapter(ctx context.Context, lc Adapter) context.Context {
return context.WithValue(ctx, adapterKey, lc)
}
func adapterFromContext(ctx context.Context) Adapter {
lc, _ := ctx.Value(adapterKey).(Adapter)
return lc
}
// CallerDepthFromContext return callerDepth int value, this value is used by finding caller position, usually doesn't have to remember it.
func CallDepthFromContext(ctx context.Context) int {
if ctx == nil {
return 0
}
cd, _ := ctx.Value(callDepthKey).(int)
return cd
}
// withAddingCallDepth returns a new context that has incremented call depth to log. Used with wrapped or utilized logger functions.
func withAddingCallDepth(ctx context.Context, depth int) context.Context {
return context.WithValue(ctx, callDepthKey, CallDepthFromContext(ctx)+depth)
}