This repository has been archived by the owner on Nov 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.go
284 lines (239 loc) · 8.43 KB
/
builder.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package clog
import (
"context"
"fmt"
"reflect"
"github.com/alcionai/clues"
"go.uber.org/zap"
"golang.org/x/exp/maps"
)
// ------------------------------------------------------------------------------------------------
// builder is the primary logging handler
// most funcs that people would use in the daily drive are going
// to modfiy and/or return a builder instance. The builder aggregates
// data passed to it until a log func is called (debug, info, or error).
// At that time it consumes all of the gathered data to send the log message.
// ------------------------------------------------------------------------------------------------
type builder struct {
ctx context.Context
err error
zsl *zap.SugaredLogger
with map[any]any
labels map[string]struct{}
comments map[string]struct{}
skipCallerJumps int
}
func newBuilder(ctx context.Context) *builder {
clgr := fromCtx(ctx)
return &builder{
ctx: ctx,
zsl: clgr.zsl,
with: map[any]any{},
labels: map[string]struct{}{},
comments: map[string]struct{}{},
}
}
// log actually delivers the log to the underlying logger with the given
func (b builder) log(l logLevel, msg string) {
cv := clues.In(b.ctx).Map()
zsl := b.zsl
if b.err != nil {
// error values should override context values.
maps.Copy(cv, clues.InErr(b.err).Map())
// attach the error and its labels
zsl = zsl.
With("error", b.err).
With("error_labels", clues.Labels(b.err))
}
for k, v := range cv {
zsl = zsl.With(k, v)
}
// plus any values added using builder.With()
for k, v := range b.with {
zsl = zsl.With(k, v)
}
// finally, make sure we attach the labels and comments
zsl = zsl.With("clog_labels", maps.Keys(b.labels))
zsl = zsl.With("clog_comments", maps.Keys(b.comments))
if b.skipCallerJumps > 0 {
zsl = zsl.WithOptions(zap.AddCallerSkip(b.skipCallerJumps))
}
// then write everything to the logger
switch l {
case LevelDebug:
var ok bool
for _, l := range cloggerton.set.OnlyLogDebugIfContainsLabel {
if _, match := b.labels[l]; match {
ok = true
break
}
}
if !ok {
return
}
zsl.Debug(msg)
case LevelInfo:
zsl.Info(msg)
case LevelError:
zsl.Error(msg)
}
}
// Err attaches the error to the builder.
// When logged, the error will be parsed for any clues parts
// and those values will get added to the resulting log.
//
// ex: if you have some `err := clues.New("badness").With("cause", reason)`
// then this will add both of the following to the log:
// - "error": "badness"
// - "cause": reason
func (b *builder) Err(err error) *builder {
b.err = err
return b
}
// Label adds all of the appended labels to the error.
// Adding labels is a great way to categorize your logs into broad scale
// concepts like "configuration", "process kickoff", or "process conclusion".
// they're also a great way to set up various granularities of debugging
// like "api queries" or "fine grained item review", since you can configure
// clog to automatically filter debug level logging to only deliver if the
// logs match one or more labels, allowing you to only emit some of the
// overwhelming number of debug logs that we all know you produce, you
// little overlogger, you.
func (b *builder) Label(ls ...string) *builder {
if len(b.labels) == 0 {
b.labels = map[string]struct{}{}
}
for _, l := range ls {
b.labels[l] = struct{}{}
}
return b
}
// Comments are available because why make your devs go all the way back to
// the code to find the comment about this log case? Add them into the log
// itself!
func (b *builder) Comment(cmnt string) *builder {
if len(b.comments) == 0 {
b.comments = map[string]struct{}{}
}
b.comments[cmnt] = struct{}{}
return b
}
// SkipCaller allows the logger to set its stackTrace N levels back from the
// current call. This is great for helper functions that handle log actions
// which get used by many different consumers, as it will always report the
// log line as the call to the helper function, instead of the line within the
// helper func.
func (b *builder) SkipCaller(nSkips int) *builder {
b.skipCallerJumps = nSkips
return b
}
// getValue will return the value if not pointer, or the dereferenced
// value if it is a pointer.
func getValue(v any) any {
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Ptr {
if rv.IsNil() {
return nil
}
return rv.Elem().Interface()
}
return v
}
// With is your standard "With" func. Add data in K:V pairs here to have them
// added to the log message metadata. Ex: builder.With("foo", "bar") will add
// "foo": "bar" to the resulting log structure. An uneven number of pairs will
// give the last key a nil value.
func (b *builder) With(vs ...any) *builder {
if len(vs) == 0 {
return b
}
if len(b.with) == 0 {
b.with = map[any]any{}
}
for i := 0; i < len(vs); i += 2 {
k := vs[i]
var v any
if (i + 1) < len(vs) {
v = vs[i+1]
}
b.with[k] = getValue(v)
}
return b
}
// Debug level logging. Whenever possible, you should add a debug category
// label to the log, as that will help your org maintain fine grained control
// of debug-level log filtering.
func (b builder) Debug(msgArgs ...any) {
b.log(LevelDebug, fmt.Sprint(msgArgs...))
}
// Debugf level logging. Whenever possible, you should add a debug category
// label to the log, as that will help your org maintain fine grained control
// of debug-level log filtering.
// f is for format.
// f is also for "Why? Why are you using this? Use Debugw instead, it's much better".
func (b builder) Debugf(tmpl string, vs ...any) {
b.log(LevelDebug, fmt.Sprintf(tmpl, vs...))
}
// Debugw level logging. Whenever possible, you should add a debug category
// label to the log, as that will help your org maintain fine grained control
// of debug-level log filtering.
// w is for With(key:values). log.Debugw("msg", foo, bar) is the same as
// log.With(foo, bar).Debug("msg").
func (b builder) Debugw(msg string, keyValues ...any) {
b.With(keyValues...).log(LevelDebug, msg)
}
// Info is your standard info log. You know. For information.
func (b builder) Info(msgArgs ...any) {
b.log(LevelInfo, fmt.Sprint(msgArgs...))
}
// Infof is your standard info log. You know. For information.
// f is for format.
// f is also for "Don't make bloated log messages, kids. Use Infow instead.".
func (b builder) Infof(tmpl string, vs ...any) {
b.log(LevelInfo, fmt.Sprintf(tmpl, vs...))
}
// Infow is your standard info log. You know. For information.
// w is for With(key:values). log.Infow("msg", foo, bar) is the same as
// log.With(foo, bar).Info("msg").
func (b builder) Infow(msg string, keyValues ...any) {
b.With(keyValues...).log(LevelInfo, msg)
}
// Error is an error level log. It doesn't require an error, because there's no
// rule about needing an error to log at error level. Or the reverse; feel free to
// add an error to your info or debug logs. Log levels are just a fake labeling
// system, anyway.
func (b builder) Error(msgArgs ...any) {
b.log(LevelError, fmt.Sprint(msgArgs...))
}
// Error is an error level log. It doesn't require an error, because there's no
// rule about needing an error to log at error level. Or the reverse; feel free to
// add an error to your info or debug logs. Log levels are just a fake labeling
// system, anyway.
// f is for format.
// f is also for "Good developers know the value of using Errorw before Errorf."
func (b builder) Errorf(tmpl string, vs ...any) {
b.log(LevelError, fmt.Sprintf(tmpl, vs...))
}
// Error is an error level log. It doesn't require an error, because there's no
// rule about needing an error to log at error level. Or the reverse; feel free to
// add an error to your info or debug logs. Log levels are just a fake labeling
// system, anyway.
// w is for With(key:values). log.Errorw("msg", foo, bar) is the same as
// log.With(foo, bar).Error("msg").
func (b builder) Errorw(msg string, keyValues ...any) {
b.With(keyValues...).log(LevelError, msg)
}
// ------------------------------------------------------------------------------------------------
// wrapper: io.writer
// ------------------------------------------------------------------------------------------------
// Writer is a wrapper that turns the logger embedded in
// the given ctx into an io.Writer. All logs are currently
// info-level.
type Writer struct {
Ctx context.Context
}
// Write writes to the the Writer's clogger.
func (w Writer) Write(p []byte) (int, error) {
Ctx(w.Ctx).log(LevelInfo, string(p))
return len(p), nil
}