-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfields.go
More file actions
54 lines (46 loc) · 1.11 KB
/
fields.go
File metadata and controls
54 lines (46 loc) · 1.11 KB
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
package logging
import (
"context"
)
type logsContext string
var (
contextKey logsContext = "LogsContextKey"
)
// LogFields contains all fields that have to be added to logs
type LogFields map[string]interface{}
// Add or modify log fields
func (o LogFields) Add(key string, value interface{}) {
if len(key) > 0 {
o[key] = value
}
}
// Del deletes a log field entry
func (o LogFields) Del(key string) {
delete(o, key)
}
// AddToLogContext adds log fields to context.
// Any info added here will be added to all logs using this context
func AddToLogContext(ctx context.Context, key string, value interface{}) context.Context {
data := FromContext(ctx)
if data == nil {
ctx = context.WithValue(ctx, contextKey, make(LogFields))
data = FromContext(ctx)
}
m := ctx.Value(contextKey)
if data, ok := m.(LogFields); ok {
data.Add(key, value)
}
return ctx
}
// FromContext fetchs log fields from provided context
func FromContext(ctx context.Context) LogFields {
if ctx == nil {
return nil
}
if h := ctx.Value(contextKey); h != nil {
if logData, ok := h.(LogFields); ok {
return logData
}
}
return nil
}