Debian Codegraph @

klogr/klogr.go

raw
1 // Package klogr implements github.com/go-logr/logr.Logger in terms of
2 // k8s.io/klog.
3 package klogr
4
5 import (
6 "bytes"
7 "encoding/json"
8 "fmt"
9 "sort"
10 "strings"
11
12 "github.com/go-logr/logr"
13
14 "k8s.io/klog/v2"
15 "k8s.io/klog/v2/internal/serialize"
16 )
17
18 const (
19 // nameKey is used to log the `WithName` values as an additional attribute.
20 nameKey = "logger"
21 )
22
23 // Option is a functional option that reconfigures the logger created with New.
24 type Option func(*klogger)
25
26 // Format defines how log output is produced.
27 type Format string
28
29 const (
30 // FormatSerialize tells klogr to turn key/value pairs into text itself
31 // before invoking klog. Key/value pairs are sorted by key.
32 FormatSerialize Format = "Serialize"
33
34 // FormatKlog tells klogr to pass all text messages and key/value pairs
35 // directly to klog. Klog itself then serializes in a human-readable
36 // format and optionally passes on to a structure logging backend.
37 FormatKlog Format = "Klog"
38 )
39
40 // WithFormat selects the output format.
41 func WithFormat(format Format) Option {
42 return func(l *klogger) {
43 l.format = format
44 }
45 }
46
47 // New returns a logr.Logger which serializes output itself
48 // and writes it via klog.
49 //
50 // Deprecated: this uses a custom, out-dated output format. Use textlogger.NewLogger instead.
51 func New() logr.Logger {
52 return NewWithOptions(WithFormat(FormatSerialize))
53 }
54
55 // NewWithOptions returns a logr.Logger which serializes as determined
56 // by the WithFormat option and writes via klog. The default is
57 // FormatKlog.
58 //
59 // Deprecated: FormatSerialize is out-dated. For FormatKlog, use textlogger.NewLogger instead.
60 func NewWithOptions(options ...Option) logr.Logger {
61 l := klogger{
62 level: 0,
63 values: nil,
64 format: FormatKlog,
65 }
66 for _, option := range options {
67 option(&l)
68 }
69 return logr.New(&l)
70 }
71
72 type klogger struct {
73 level int
74 callDepth int
75
76 // hasPrefix is true if the first entry in values is the special
77 // nameKey key/value. Such an entry gets added and later updated in
78 // WithName.
79 hasPrefix bool
80
81 values []interface{}
82 format Format
83 }
84
85 func (l *klogger) Init(info logr.RuntimeInfo) {
86 l.callDepth += info.CallDepth
87 }
88
89 func flatten(kvList ...interface{}) string {
90 keys := make([]string, 0, len(kvList))
91 vals := make(map[string]interface{}, len(kvList))
92 for i := 0; i < len(kvList); i += 2 {
93 k, ok := kvList[i].(string)
94 if !ok {
95 panic(fmt.Sprintf("key is not a string: %s", pretty(kvList[i])))
96 }
97 var v interface{}
98 if i+1 < len(kvList) {
99 v = kvList[i+1]
100 }
101 // Only print each key once...
102 if _, seen := vals[k]; !seen {
103 keys = append(keys, k)
104 }
105 // ... with the latest value.
106 vals[k] = v
107 }
108 sort.Strings(keys)
109 buf := bytes.Buffer{}
110 for i, k := range keys {
111 v := vals[k]
112 if i > 0 {
113 buf.WriteRune(' ')
114 }
115 buf.WriteString(pretty(k))
116 buf.WriteString("=")
117 buf.WriteString(pretty(v))
118 }
119 return buf.String()
120 }
121
122 func pretty(value interface{}) string {
123 if err, ok := value.(error); ok {
124 if _, ok := value.(json.Marshaler); !ok {
125 value = err.Error()
126 }
127 }
128 buffer := &bytes.Buffer{}
129 encoder := json.NewEncoder(buffer)
130 encoder.SetEscapeHTML(false)
131 if err := encoder.Encode(value); err != nil {
132 return fmt.Sprintf("<<error: %v>>", err)
133 }
134 return strings.TrimSpace(buffer.String())
135 }
136
137 func (l *klogger) Info(level int, msg string, kvList ...interface{}) {
138 switch l.format {
139 case FormatSerialize:
140 msgStr := flatten("msg", msg)
141 merged := serialize.MergeKVs(l.values, kvList)
142 kvStr := flatten(merged...)
143 klog.VDepth(l.callDepth+1, klog.Level(level)).InfoDepth(l.callDepth+1, msgStr, " ", kvStr)
144 case FormatKlog:
145 merged := serialize.MergeKVs(l.values, kvList)
146 klog.VDepth(l.callDepth+1, klog.Level(level)).InfoSDepth(l.callDepth+1, msg, merged...)
147 }
148 }
149
150 func (l *klogger) Enabled(level int) bool {
151 return klog.VDepth(l.callDepth+1, klog.Level(level)).Enabled()
152 }
153
154 func (l *klogger) Error(err error, msg string, kvList ...interface{}) {
155 msgStr := flatten("msg", msg)
156 var loggableErr interface{}
157 if err != nil {
158 loggableErr = serialize.ErrorToString(err)
159 }
160 switch l.format {
161 case FormatSerialize:
162 errStr := flatten("error", loggableErr)
163 merged := serialize.MergeKVs(l.values, kvList)
164 kvStr := flatten(merged...)
165 klog.ErrorDepth(l.callDepth+1, msgStr, " ", errStr, " ", kvStr)
166 case FormatKlog:
167 merged := serialize.MergeKVs(l.values, kvList)
168 klog.ErrorSDepth(l.callDepth+1, err, msg, merged...)
169 }
170 }
171
172 // WithName returns a new logr.Logger with the specified name appended. klogr
173 // uses '.' characters to separate name elements. Callers should not pass '.'
174 // in the provided name string, but this library does not actually enforce that.
175 func (l klogger) WithName(name string) logr.LogSink {
176 if l.hasPrefix {
177 // Copy slice and modify value. No length checks and type
178 // assertions are needed because hasPrefix is only true if the
179 // first two elements exist and are key/value strings.
180 v := make([]interface{}, 0, len(l.values))
181 v = append(v, l.values...)
182 prefix, _ := v[1].(string)
183 prefix = prefix + "." + name
184 v[1] = prefix
185 l.values = v
186 } else {
187 // Preprend new key/value pair.
188 v := make([]interface{}, 0, 2+len(l.values))
189 v = append(v, nameKey, name)
190 v = append(v, l.values...)
191 l.values = v
192 l.hasPrefix = true
193 }
194 return &l
195 }
196
197 func (l klogger) WithValues(kvList ...interface{}) logr.LogSink {
198 l.values = serialize.WithValues(l.values, kvList)
199 return &l
200 }
201
202 func (l klogger) WithCallDepth(depth int) logr.LogSink {
203 l.callDepth += depth
204 return &l
205 }
206
207 var _ logr.LogSink = &klogger{}
208 var _ logr.CallDepthLogSink = &klogger{}