This repository has been archived by the owner on Apr 27, 2023. It is now read-only.
forked from istio/istio
-
Notifications
You must be signed in to change notification settings - Fork 7
/
options.go
397 lines (336 loc) · 13.1 KB
/
options.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
// 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
import (
"fmt"
"sort"
"strings"
"github.com/spf13/cobra"
)
const (
// DefaultScopeName defines the name of the default scope.
DefaultScopeName = "default"
defaultOutputLevel = InfoLevel
defaultStackTraceLevel = NoneLevel
defaultOutputPath = "stdout"
defaultErrorOutputPath = "stderr"
defaultRotationMaxAge = 30
defaultRotationMaxSize = 100 * 1024 * 1024
defaultRotationMaxBackups = 1000
)
// Level is an enumeration of all supported log levels.
type Level int
const (
// NoneLevel disables logging
NoneLevel Level = iota
// ErrorLevel enables error level logging
ErrorLevel
// WarnLevel enables warn level logging
WarnLevel
// InfoLevel enables info level logging
InfoLevel
// DebugLevel enables debug level logging
DebugLevel
)
var levelToString = map[Level]string{
DebugLevel: "debug",
InfoLevel: "info",
WarnLevel: "warn",
ErrorLevel: "error",
NoneLevel: "none",
}
var stringToLevel = map[string]Level{
"debug": DebugLevel,
"info": InfoLevel,
"warn": WarnLevel,
"error": ErrorLevel,
"none": NoneLevel,
}
// Options defines the set of options supported by Istio's component logging package.
type Options struct {
// OutputPaths is a list of file system paths to write the log data to.
// The special values stdout and stderr can be used to output to the
// standard I/O streams. This defaults to stdout.
OutputPaths []string
// ErrorOutputPaths is a list of file system paths to write logger errors to.
// The special values stdout and stderr can be used to output to the
// standard I/O streams. This defaults to stderr.
ErrorOutputPaths []string
// RotateOutputPath is the path to a rotating log file. This file should
// be automatically rotated over time, based on the rotation parameters such
// as RotationMaxSize and RotationMaxAge. The default is to not rotate.
//
// This path is used as a foundational path. This is where log output is normally
// saved. When a rotation needs to take place because the file got too big or too
// old, then the file is renamed by appending a timestamp to the name. Such renamed
// files are called backups. Once a backup has been created,
// output resumes to this path.
RotateOutputPath string
// RotationMaxSize is the maximum size in megabytes of a log file before it gets
// rotated. It defaults to 100 megabytes.
RotationMaxSize int
// RotationMaxAge is the maximum number of days to retain old log files based on the
// timestamp encoded in their filename. Note that a day is defined as 24
// hours and may not exactly correspond to calendar days due to daylight
// savings, leap seconds, etc. The default is to remove log files
// older than 30 days.
RotationMaxAge int
// RotationMaxBackups is the maximum number of old log files to retain. The default
// is to retain at most 1000 logs.
RotationMaxBackups int
// JSONEncoding controls whether the log is formatted as JSON.
JSONEncoding bool
// LogGrpc indicates that Grpc logs should be captured. The default is true.
// This is not exposed through the command-line flags, as this flag is mainly useful for testing: Grpc
// stack will hold on to the logger even though it gets closed. This causes data races.
LogGrpc bool
outputLevels string
logCallers string
stackTraceLevels string
}
// DefaultOptions returns a new set of options, initialized to the defaults
func DefaultOptions() *Options {
return &Options{
OutputPaths: []string{defaultOutputPath},
ErrorOutputPaths: []string{defaultErrorOutputPath},
RotationMaxSize: defaultRotationMaxSize,
RotationMaxAge: defaultRotationMaxAge,
RotationMaxBackups: defaultRotationMaxBackups,
outputLevels: DefaultScopeName + ":" + levelToString[defaultOutputLevel],
stackTraceLevels: DefaultScopeName + ":" + levelToString[defaultStackTraceLevel],
LogGrpc: true,
}
}
// SetOutputLevel sets the minimum log output level for a given scope.
func (o *Options) SetOutputLevel(scope string, level Level) {
sl := scope + ":" + levelToString[level]
levels := strings.Split(o.outputLevels, ",")
if scope == DefaultScopeName {
// see if we have an entry without a scope prefix (which represents the default scope)
for i, ol := range levels {
if !strings.Contains(ol, ":") {
levels[i] = sl
o.outputLevels = strings.Join(levels, ",")
return
}
}
}
prefix := scope + ":"
for i, ol := range levels {
if strings.HasPrefix(ol, prefix) {
levels[i] = sl
o.outputLevels = strings.Join(levels, ",")
return
}
}
levels = append(levels, sl)
o.outputLevels = strings.Join(levels, ",")
}
// GetOutputLevel returns the minimum log output level for a given scope.
func (o *Options) GetOutputLevel(scope string) (Level, error) {
levels := strings.Split(o.outputLevels, ",")
if scope == DefaultScopeName {
// see if we have an entry without a scope prefix (which represents the default scope)
for _, ol := range levels {
if !strings.Contains(ol, ":") {
_, l, err := convertScopedLevel(ol)
return l, err
}
}
}
prefix := scope + ":"
for _, ol := range levels {
if strings.HasPrefix(ol, prefix) {
_, l, err := convertScopedLevel(ol)
return l, err
}
}
return NoneLevel, fmt.Errorf("no level defined for scope '%s'", scope)
}
// SetStackTraceLevel sets the minimum stack tracing level for a given scope.
func (o *Options) SetStackTraceLevel(scope string, level Level) {
sl := scope + ":" + levelToString[level]
levels := strings.Split(o.stackTraceLevels, ",")
if scope == DefaultScopeName {
// see if we have an entry without a scope prefix (which represents the default scope)
for i, ol := range levels {
if !strings.Contains(ol, ":") {
levels[i] = sl
o.stackTraceLevels = strings.Join(levels, ",")
return
}
}
}
prefix := scope + ":"
for i, ol := range levels {
if strings.HasPrefix(ol, prefix) {
levels[i] = sl
o.stackTraceLevels = strings.Join(levels, ",")
return
}
}
levels = append(levels, sl)
o.stackTraceLevels = strings.Join(levels, ",")
}
// GetStackTraceLevel returns the minimum stack tracing level for a given scope.
func (o *Options) GetStackTraceLevel(scope string) (Level, error) {
levels := strings.Split(o.stackTraceLevels, ",")
if scope == DefaultScopeName {
// see if we have an entry without a scope prefix (which represents the default scope)
for _, ol := range levels {
if !strings.Contains(ol, ":") {
_, l, err := convertScopedLevel(ol)
return l, err
}
}
}
prefix := scope + ":"
for _, ol := range levels {
if strings.HasPrefix(ol, prefix) {
_, l, err := convertScopedLevel(ol)
return l, err
}
}
return NoneLevel, fmt.Errorf("no level defined for scope '%s'", scope)
}
// SetLogCallers sets whether to output the caller's source code location for a given scope.
func (o *Options) SetLogCallers(scope string, include bool) {
scopes := strings.Split(o.logCallers, ",")
// remove any occurrence of the scope
for i, s := range scopes {
if s == scope {
scopes[i] = ""
}
}
if include {
// find a free slot if there is one
for i, s := range scopes {
if s == "" {
scopes[i] = scope
o.logCallers = strings.Join(scopes, ",")
return
}
}
scopes = append(scopes, scope)
}
o.logCallers = strings.Join(scopes, ",")
}
// GetLogCallers returns whether the caller's source code location is output for a given scope.
func (o *Options) GetLogCallers(scope string) bool {
scopes := strings.Split(o.logCallers, ",")
for _, s := range scopes {
if s == scope {
return true
}
}
return false
}
func convertScopedLevel(sl string) (string, Level, error) {
var s string
var l string
pieces := strings.Split(sl, ":")
if len(pieces) == 1 {
s = DefaultScopeName
l = pieces[0]
} else if len(pieces) == 2 {
s = pieces[0]
l = pieces[1]
} else {
return "", NoneLevel, fmt.Errorf("invalid output level format '%s'", sl)
}
level, ok := stringToLevel[l]
if !ok {
return "", NoneLevel, fmt.Errorf("invalid output level '%s'", sl)
}
return s, level, nil
}
// AttachCobraFlags attaches a set of Cobra flags to the given Cobra command.
//
// Cobra is the command-line processor that Istio uses. This command attaches
// the necessary set of flags to expose a CLI to let the user control all
// logging options.
func (o *Options) AttachCobraFlags(cmd *cobra.Command) {
cmd.PersistentFlags().StringArrayVar(&o.OutputPaths, "log_target", o.OutputPaths,
"The set of paths where to output the log. This can be any path as well as the special values stdout and stderr")
cmd.PersistentFlags().StringVar(&o.RotateOutputPath, "log_rotate", o.RotateOutputPath,
"The path for the optional rotating log file")
cmd.PersistentFlags().IntVar(&o.RotationMaxAge, "log_rotate_max_age", o.RotationMaxAge,
"The maximum age in days of a log file beyond which the file is rotated (0 indicates no limit)")
cmd.PersistentFlags().IntVar(&o.RotationMaxSize, "log_rotate_max_size", o.RotationMaxSize,
"The maximum size in megabytes of a log file beyond which the file is rotated")
cmd.PersistentFlags().IntVar(&o.RotationMaxBackups, "log_rotate_max_backups", o.RotationMaxBackups,
"The maximum number of log file backups to keep before older files are deleted (0 indicates no limit)")
cmd.PersistentFlags().BoolVar(&o.JSONEncoding, "log_as_json", o.JSONEncoding,
"Whether to format output as JSON or in plain console-friendly format")
allScopes := Scopes()
if len(allScopes) > 1 {
keys := make([]string, 0, len(allScopes))
for name := range allScopes {
keys = append(keys, name)
}
sort.Strings(keys)
s := strings.Join(keys, ", ")
cmd.PersistentFlags().StringVar(&o.outputLevels, "log_output_level", o.outputLevels,
fmt.Sprintf("Comma-separated minimum per-scope logging level of messages to output, in the form of "+
"<scope>:<level>,<scope>:<level>,... where scope can be one of [%s] and level can be one of [%s, %s, %s, %s, %s]",
s,
levelToString[DebugLevel],
levelToString[InfoLevel],
levelToString[WarnLevel],
levelToString[ErrorLevel],
levelToString[NoneLevel]))
cmd.PersistentFlags().StringVar(&o.stackTraceLevels, "log_stacktrace_level", o.stackTraceLevels,
fmt.Sprintf("Comma-separated minimum per-scope logging level at which stack traces are captured, in the form of "+
"<scope>:<level>,<scope:level>,... where scope can be one of [%s] and level can be one of [%s, %s, %s, %s, %s]",
s,
levelToString[DebugLevel],
levelToString[InfoLevel],
levelToString[WarnLevel],
levelToString[ErrorLevel],
levelToString[NoneLevel]))
cmd.PersistentFlags().StringVar(&o.logCallers, "log_caller", o.logCallers,
fmt.Sprintf("Comma-separated list of scopes for which to include caller information, scopes can be any of [%s]", s))
} else {
cmd.PersistentFlags().StringVar(&o.outputLevels, "log_output_level", o.outputLevels,
fmt.Sprintf("The minimum logging level of messages to output, can be one of [%s, %s, %s, %s, %s]",
levelToString[DebugLevel],
levelToString[InfoLevel],
levelToString[WarnLevel],
levelToString[ErrorLevel],
levelToString[NoneLevel]))
cmd.PersistentFlags().StringVar(&o.stackTraceLevels, "log_stacktrace_level", o.stackTraceLevels,
fmt.Sprintf("The minimum logging level at which stack traces are captured, can be one of [%s, %s, %s, %s, %s]",
levelToString[DebugLevel],
levelToString[InfoLevel],
levelToString[WarnLevel],
levelToString[ErrorLevel],
levelToString[NoneLevel]))
cmd.PersistentFlags().StringVar(&o.logCallers, "log_caller", o.logCallers,
"Comma-separated list of scopes for which to include called information, scopes can be any of [default]")
}
// NOTE: we don't currently expose a command-line option to control ErrorOutputPaths since it
// seems too esoteric.
// TODO: Remove all this stuff by the 1.0 release
var dummy string
var dummy2 bool
cmd.PersistentFlags().StringVarP(&dummy, "v", "v", "", "deprecated")
cmd.PersistentFlags().StringVarP(&dummy, "stderrthreshold", "", "", "deprecated")
cmd.PersistentFlags().BoolVarP(&dummy2, "alsologtostderr", "", false, "deprecated")
cmd.PersistentFlags().BoolVarP(&dummy2, "logtostderr", "", false, "deprecated")
_ = cmd.PersistentFlags().MarkDeprecated("v", "please use --log_output_level instead")
_ = cmd.PersistentFlags().MarkShorthandDeprecated("v", "please use --log_output_level instead")
_ = cmd.PersistentFlags().MarkDeprecated("stderrthreshold", "please use --log_output_level instead")
_ = cmd.PersistentFlags().MarkDeprecated("logtostderr", "please use --log_target instead")
_ = cmd.PersistentFlags().MarkDeprecated("alsologtostderr", "please use --log_target instead")
}