-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.go
348 lines (301 loc) · 9.38 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
// Copyright (c) Tetrate, Inc 2018 All Rights Reserved.
// 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.AttachFlags(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 (
"fmt"
"os"
"sort"
"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"
)
// none is used to disable logging output as well as to disable stack tracing.
const none zapcore.Level = 100
var levelToZap = map[Level]zapcore.Level{
DebugLevel: zapcore.DebugLevel,
InfoLevel: zapcore.InfoLevel,
WarnLevel: zapcore.WarnLevel,
ErrorLevel: zapcore.ErrorLevel,
NoneLevel: none,
}
func init() {
// use our defaults for starters so that logging works even before everything is fully configured
_ = Configure(DefaultOptions())
}
// prepZap is a utility function used by the Configure function.
func prepZap(options *Options) (zapcore.Core, zapcore.Core, zapcore.WriteSyncer, error) {
encCfg := 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,
}
var enc zapcore.Encoder
if options.JSONEncoding {
enc = zapcore.NewJSONEncoder(encCfg)
} else {
enc = zapcore.NewConsoleEncoder(encCfg)
}
var rotaterSink zapcore.WriteSyncer
if options.RotateOutputPath != "" {
rotaterSink = zapcore.AddSync(&lumberjack.Logger{
Filename: options.RotateOutputPath,
MaxSize: options.RotationMaxSize,
MaxBackups: options.RotationMaxAge,
MaxAge: options.RotationMaxBackups,
})
}
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
}
var enabler zap.LevelEnablerFunc = func(lvl zapcore.Level) bool {
switch lvl {
case zapcore.ErrorLevel:
return defaultScope.ErrorEnabled()
case zapcore.WarnLevel:
return defaultScope.WarnEnabled()
case zapcore.InfoLevel:
return defaultScope.InfoEnabled()
}
return defaultScope.DebugEnabled()
}
return zapcore.NewCore(enc, sink, zap.NewAtomicLevelAt(zapcore.DebugLevel)),
zapcore.NewCore(enc, sink, enabler),
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, core zapcore.Core, errSink zapcore.WriteSyncer) error {
// init the global I/O funcs
writeFn.Store(core.Write)
syncFn.Store(core.Sync)
errorSink.Store(errSink)
// snapshot what's there
allScopes := Scopes()
// update the output levels of all scopes
if err := processLevels(allScopes, options.outputLevels, func(s *Scope, l Level) { s.SetOutputLevel(l) }); err != nil {
return err
}
// update the stack tracing levels of all 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 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)
}
return nil
}
if scope, ok := allScopes[s]; ok {
scope.SetLogCallers(true)
} else {
_, _ = fmt.Fprintf(os.Stderr, "unknown scope '%s' specified", s)
}
}
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
} else {
_, _ = fmt.Fprintf(os.Stderr, "unknown scope '%s' specified\n", s)
}
}
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.
func Configure(options *Options) error {
core, captureCore, errSink, err := prepZap(options)
if err != nil {
return err
}
if err = updateScopes(options, core, errSink); err != nil {
return err
}
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]))
}
captureLogger := zap.New(captureCore, opts...)
// capture global zap logging and force it through our logger
_ = zap.ReplaceGlobals(captureLogger)
// capture standard golang "log" package output and force it through our logger
_ = zap.RedirectStdLog(captureLogger)
// capture gRPC logging
if options.LogGrpc {
// TODO(https://github.com/uber-go/zap/issues/534): remove the nolint directive
grpclog.SetLogger(zapgrpc.NewLogger(captureLogger.WithOptions(zap.AddCallerSkip(2)))) //nolint: megacheck
}
return nil
}
// reset by the Configure method
var syncFn atomic.Value
// Sync flushes any buffered log entries.
// Processes should normally take care to call Sync before exiting.
func Sync() error {
var err error
if s := syncFn.Load().(func() error); s != nil {
err = s()
}
return err
}
// PrintRegisteredScopes logs all the registered scopes and their configured output level using` the default logger
func PrintRegisteredScopes() {
s := Scopes()
pad := 0
names := make([]string, 0, len(s))
for n := range s {
names = append(names, n)
if len(n) > pad {
pad = len(n)
}
}
sort.Strings(names)
Info("registered logging scopes:")
for _, n := range names {
sc := s[n]
Infof("- %-*s %-5s %s", pad, sc.Name(), levelToString[sc.GetOutputLevel()], sc.Description())
}
}