/
config.go
440 lines (389 loc) · 12.1 KB
/
config.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
// Copyright 2017 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package log provides the canonical logging functionality used by Go-based
// Istio components.
//
// Istio's logging subsystem is built on top of the [Zap](https://godoc.org/go.uber.org/zap) package.
// High performance scenarios should use the Error, Warn, Info, and Debug methods. Lower perf
// scenarios can use the more expensive convenience methods such as Debugf and Warnw.
//
// The package provides direct integration with the Cobra command-line processor which makes it
// easy to build programs that use a consistent interface for logging. Here's an example
// of a simple Cobra-based program using this log package:
//
// func main() {
// // get the default logging options
// options := log.DefaultOptions()
//
// rootCmd := &cobra.Command{
// Run: func(cmd *cobra.Command, args []string) {
//
// // configure the logging system
// if err := log.Configure(options); err != nil {
// // print an error and quit
// }
//
// // output some logs
// log.Info("Hello")
// log.Sync()
// },
// }
//
// // add logging-specific flags to the cobra command
// options.AttachCobraFlags(rootCmd)
// rootCmd.SetArgs(os.Args[1:])
// rootCmd.Execute()
// }
//
// Once configured, this package intercepts the output of the standard golang "log" package as well as anything
// sent to the global zap logger (zap.L()).
package log
import (
"os"
"strings"
"sync/atomic"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zapgrpc"
"google.golang.org/grpc/grpclog"
"gopkg.in/natefinch/lumberjack.v2"
"k8s.io/klog/v2"
)
const (
// none is used to disable logging output as well as to disable stack tracing.
none zapcore.Level = 100
GrpcScopeName string = "grpc"
)
var levelToZap = map[Level]zapcore.Level{
DebugLevel: zapcore.DebugLevel,
InfoLevel: zapcore.InfoLevel,
WarnLevel: zapcore.WarnLevel,
ErrorLevel: zapcore.ErrorLevel,
FatalLevel: zapcore.FatalLevel,
NoneLevel: none,
}
var defaultEncoderConfig = zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "scope",
CallerKey: "caller",
MessageKey: "msg",
StacktraceKey: "stack",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
EncodeDuration: zapcore.StringDurationEncoder,
EncodeTime: formatDate,
}
// functions that can be replaced in a test setting
type patchTable struct {
write func(ent zapcore.Entry, fields []zapcore.Field) error
sync func() error
exitProcess func(code int)
errorSink zapcore.WriteSyncer
close func() error
}
var (
// function table that can be replaced by tests
funcs = &atomic.Value{}
// controls whether all output is JSON or CLI style. This makes it easier to query how the zap encoder is configured
// vs. reading it's internal state.
useJSON atomic.Value
)
func init() {
// use our defaults for starters so that logging works even before everything is fully configured
_ = Configure(DefaultOptions())
}
// See: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity
var stackdriverSeverityMapping = map[zapcore.Level]string{
zapcore.DebugLevel: "Debug",
zapcore.InfoLevel: "Info",
zapcore.WarnLevel: "Warning",
zapcore.ErrorLevel: "Error",
zapcore.DPanicLevel: "Critical",
zapcore.FatalLevel: "Critical",
zapcore.PanicLevel: "Critical",
}
func encodeStackdriverLevel(l zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(stackdriverSeverityMapping[l])
}
// prepZap sets up the core Zap loggers
func prepZap(options *Options) (zapcore.Core, func(string) zapcore.Core, zapcore.WriteSyncer, error) {
var enc zapcore.Encoder
if options.useStackdriverFormat {
// See also: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
encCfg := zapcore.EncoderConfig{
TimeKey: "timestamp",
LevelKey: "severity",
NameKey: "logger",
CallerKey: "caller",
MessageKey: "message",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: encodeStackdriverLevel,
EncodeTime: zapcore.RFC3339NanoTimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
}
enc = zapcore.NewJSONEncoder(encCfg)
useJSON.Store(true)
} else {
encCfg := defaultEncoderConfig
if options.JSONEncoding {
enc = zapcore.NewJSONEncoder(encCfg)
useJSON.Store(true)
} else {
enc = zapcore.NewConsoleEncoder(encCfg)
useJSON.Store(false)
}
}
var rotaterSink zapcore.WriteSyncer
if options.RotateOutputPath != "" {
rotaterSink = zapcore.AddSync(&lumberjack.Logger{
Filename: options.RotateOutputPath,
MaxSize: options.RotationMaxSize,
MaxBackups: options.RotationMaxBackups,
MaxAge: options.RotationMaxAge,
})
}
errSink, closeErrorSink, err := zap.Open(options.ErrorOutputPaths...)
if err != nil {
return nil, nil, nil, err
}
var outputSink zapcore.WriteSyncer
if len(options.OutputPaths) > 0 {
outputSink, _, err = zap.Open(options.OutputPaths...)
if err != nil {
closeErrorSink()
return nil, nil, nil, err
}
}
var sink zapcore.WriteSyncer
if rotaterSink != nil && outputSink != nil {
sink = zapcore.NewMultiWriteSyncer(outputSink, rotaterSink)
} else if rotaterSink != nil {
sink = rotaterSink
} else {
sink = outputSink
}
alwaysOn := zapcore.NewCore(enc, sink, zap.NewAtomicLevelAt(zapcore.DebugLevel))
conditionallyOn := func(scopeName string) zapcore.Core {
scope := FindScope(scopeName)
enabler := func(lvl zapcore.Level) bool {
switch lvl {
case zapcore.ErrorLevel:
return scope.ErrorEnabled()
case zapcore.WarnLevel:
return scope.WarnEnabled()
case zapcore.InfoLevel:
return scope.InfoEnabled()
}
return scope.DebugEnabled()
}
return zapcore.NewCore(enc, sink, zap.LevelEnablerFunc(enabler))
}
return alwaysOn,
conditionallyOn,
errSink, nil
}
func formatDate(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
t = t.UTC()
year, month, day := t.Date()
hour, minute, second := t.Clock()
micros := t.Nanosecond() / 1000
buf := make([]byte, 27)
buf[0] = byte((year/1000)%10) + '0'
buf[1] = byte((year/100)%10) + '0'
buf[2] = byte((year/10)%10) + '0'
buf[3] = byte(year%10) + '0'
buf[4] = '-'
buf[5] = byte((month)/10) + '0'
buf[6] = byte((month)%10) + '0'
buf[7] = '-'
buf[8] = byte((day)/10) + '0'
buf[9] = byte((day)%10) + '0'
buf[10] = 'T'
buf[11] = byte((hour)/10) + '0'
buf[12] = byte((hour)%10) + '0'
buf[13] = ':'
buf[14] = byte((minute)/10) + '0'
buf[15] = byte((minute)%10) + '0'
buf[16] = ':'
buf[17] = byte((second)/10) + '0'
buf[18] = byte((second)%10) + '0'
buf[19] = '.'
buf[20] = byte((micros/100000)%10) + '0'
buf[21] = byte((micros/10000)%10) + '0'
buf[22] = byte((micros/1000)%10) + '0'
buf[23] = byte((micros/100)%10) + '0'
buf[24] = byte((micros/10)%10) + '0'
buf[25] = byte((micros)%10) + '0'
buf[26] = 'Z'
enc.AppendString(string(buf))
}
func updateScopes(options *Options) error {
// snapshot what's there
allScopes := Scopes()
// Join defaultOutputLevels and outputLevels
levels := options.defaultOutputLevels
if levels == "" {
levels = options.outputLevels
} else if options.outputLevels != "" {
levels = levels + "," + options.outputLevels
}
// update the output levels of all listed scopes
if err := processLevels(allScopes, levels, func(s *Scope, l Level) { s.SetOutputLevel(l) }); err != nil {
return err
}
// update the stack tracing levels of all listed scopes
if err := processLevels(allScopes, options.stackTraceLevels, func(s *Scope, l Level) { s.SetStackTraceLevel(l) }); err != nil {
return err
}
// update the caller location setting of all listed scopes
sc := strings.Split(options.logCallers, ",")
for _, s := range sc {
if s == "" {
continue
}
if s == OverrideScopeName {
// ignore everything else and just apply the override value
for _, scope := range allScopes {
scope.SetLogCallers(true)
}
}
if scope, ok := allScopes[s]; ok {
scope.SetLogCallers(true)
}
}
// If gRPC logging is enabled, turn on gRPC logging automatically
if grpcScope.GetOutputLevel() != NoneLevel {
options.logGRPC = true
}
return nil
}
// processLevels breaks down an argument string into a set of scope & levels and then
// tries to apply the result to the scopes. It supports the use of a global override.
func processLevels(allScopes map[string]*Scope, arg string, setter func(*Scope, Level)) error {
levels := strings.Split(arg, ",")
for _, sl := range levels {
s, l, err := convertScopedLevel(sl)
if err != nil {
return err
}
if scope, ok := allScopes[s]; ok {
setter(scope, l)
} else if s == OverrideScopeName {
// override replaces everything
for _, scope := range allScopes {
setter(scope, l)
}
}
}
return nil
}
// Configure initializes Istio's logging subsystem.
//
// You typically call this once at process startup.
// Once this call returns, the logging system is ready to accept data.
// nolint: staticcheck
func Configure(options *Options) error {
if err := updateScopes(options); err != nil {
return err
}
baseLogger, logBuilder, errSink, err := prepZap(options)
if err != nil {
return err
}
defaultLogger := logBuilder(DefaultScopeName)
allLoggers := []*zapcore.Core{&baseLogger, &defaultLogger}
var grpcLogger zapcore.Core
if options.logGRPC {
grpcLogger = logBuilder(GrpcScopeName)
allLoggers = append(allLoggers, &grpcLogger)
}
closeFns := make([]func() error, 0)
for _, ext := range options.extensions {
for _, logger := range allLoggers {
newLogger, closeFn, err := ext(*logger)
if err != nil {
return err
}
*logger = newLogger
closeFns = append(closeFns, closeFn)
}
}
pt := patchTable{
write: func(ent zapcore.Entry, fields []zapcore.Field) error {
err := baseLogger.Write(ent, fields)
if ent.Level == zapcore.FatalLevel {
funcs.Load().(patchTable).exitProcess(1)
}
return err
},
sync: baseLogger.Sync,
exitProcess: os.Exit,
errorSink: errSink,
close: func() error {
// best-effort to sync
baseLogger.Sync() // nolint: errcheck
for _, f := range closeFns {
if err := f(); err != nil {
return err
}
}
return nil
},
}
funcs.Store(pt)
opts := []zap.Option{
zap.ErrorOutput(errSink),
zap.AddCallerSkip(1),
}
if defaultScope.GetLogCallers() {
opts = append(opts, zap.AddCaller())
}
l := defaultScope.GetStackTraceLevel()
if l != NoneLevel {
opts = append(opts, zap.AddStacktrace(levelToZap[l]))
}
defaultZapLogger := zap.New(defaultLogger, opts...)
// capture global zap logging and force it through our logger
_ = zap.ReplaceGlobals(defaultZapLogger)
// capture standard golang "log" package output and force it through our logger
_ = zap.RedirectStdLog(defaultZapLogger)
// capture gRPC logging
if options.logGRPC {
grpclog.SetLoggerV2(zapgrpc.NewLogger(zap.New(grpcLogger, opts...).WithOptions(zap.AddCallerSkip(3))))
}
// capture klog (Kubernetes logging) through our logging
configureKlog.Do(func() {
klog.SetLogger(NewLogrAdapter(KlogScope))
})
// --vklog is non zero then KlogScope should be increased.
// klog is a special case.
if klogVerbose() {
KlogScope.SetOutputLevel(DebugLevel)
}
return nil
}
// Sync flushes any buffered log entries.
// Processes should normally take care to call Sync before exiting.
func Sync() error {
return funcs.Load().(patchTable).sync()
}
// Close implements io.Closer.
func Close() error {
return funcs.Load().(patchTable).close()
}