-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlabels.go
69 lines (55 loc) · 1.62 KB
/
labels.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
// Copyright 2022 The zapcl Authors
// SPDX-License-Identifier: BSD-3-Clause
package zapcl
import (
"sync"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const (
// LabelsKeys is the value of this field must be a structured record. For more information.
//
// labels field:
// - https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#FIELDS.labels
LabelsKey = "logging.googleapis.com/labels"
)
// Label adds the Cloud Logging "labels" field from key and val.
//
// Cloud Logging truncates label keys that exceed 512 B and label values that exceed 64 KB upon their associated log entry being written.
// The truncation is indicated by an ellipsis at the end of the character string.
func Label(key, val string) zapcore.Field {
return zap.String("labels."+key, val)
}
// labelMap map of labels.
type labelMap struct {
m sync.Map
}
// Add adds the val for a key.
func (l *labelMap) Add(key, val string) {
l.m.Store(key, val)
}
// Delete deletes the value for a key.
func (l *labelMap) Delete(key string) {
l.m.Delete(key)
}
// MarshalLogObject implements zapcore.ObjectMarshaler.
func (l *labelMap) MarshalLogObject(enc zapcore.ObjectEncoder) error {
l.m.Range(func(key, val any) bool {
enc.AddString(key.(string), val.(string))
return true
})
return nil
}
// Label adds the Cloud Logging "labels" field from keyvals.
func Labels(keyvals ...string) zapcore.Field {
if len(keyvals)%2 != 0 {
panic("keyval length should be powers of two")
}
fields := new(labelMap)
for i := 0; i < len(keyvals)/2; i++ {
key := keyvals[i]
val := keyvals[i+1]
fields.Add(key, val)
}
return zap.Object(LabelsKey, fields)
}