-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecord.go
71 lines (61 loc) · 1.54 KB
/
record.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
package glog
import "context"
// NewRecordWithCapacity returns a new Record with the given capacity.
func NewRecordWithCapacity(capacity int) *Record {
return &Record{fields: make([]Field, 0, capacity)}
}
type Record struct {
fields []Field
}
func (r *Record) AddFields(fields ...Field) {
r.fields = append(r.fields, fields...)
}
func (r *Record) Add(args ...any) {
r.fields = append(r.fields, argsToFields(args)...)
}
func (r *Record) Fields() []Field {
return r.fields
}
type ContextHandler func(ctx context.Context, record *Record)
// BuildContextHandler builds a ContextHandler from key and alias.
// key is the context key for the value.
// alias is an optional alias for the field key.
func BuildContextHandler(key string, alias ...string) ContextHandler {
fieldName := key
if len(alias) > 0 && alias[0] != "" {
fieldName = alias[0]
}
return func(ctx context.Context, record *Record) {
if v := ctx.Value(key); v != nil {
record.AddFields(Any(fieldName, v))
}
}
}
const (
badKey = "!BADKEY"
noValue = "!NOVALUE"
)
// argsToFields converts arguments to fields.
func argsToFields(args []any) (fields []Field) {
fields = make([]Field, 0, len(args))
if len(args) == 0 {
return
}
argsLen := len(args)
for i := 0; i < argsLen; i++ {
switch v := args[i].(type) {
case Field:
fields = append(fields, v)
case string:
if i == argsLen-1 {
fields = append(fields, String(noValue, v))
return
}
fields = append(fields, Any(v, args[i+1]))
i += 1
default:
fields = append(fields, Any(badKey, v))
}
}
return
}