1 // Copyright 2019 The Operator-SDK Authors
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
23 "github.com/spf13/pflag"
25 "go.uber.org/zap/zapcore"
30 zapFlagSet *pflag.FlagSet
33 encoderVal encoderValue
39 zapFlagSet = pflag.NewFlagSet("zap", pflag.ExitOnError)
40 zapFlagSet.BoolVar(&development, "zap-devel", false, "Enable zap development mode (changes defaults to console encoder, debug log level, and disables sampling)")
41 zapFlagSet.Var(&encoderVal, "zap-encoder", "Zap log encoding ('json' or 'console')")
42 zapFlagSet.Var(&levelVal, "zap-level", "Zap log level (one of 'debug', 'info', 'error' or any integer value > 0)")
43 zapFlagSet.Var(&sampleVal, "zap-sample", "Enable zap log sampling. Sampling will be disabled for integer log levels > 1")
46 // FlagSet - The zap logging flagset.
47 func FlagSet() *pflag.FlagSet {
51 type encoderValue struct {
53 encoder zapcore.Encoder
57 func (v *encoderValue) Set(e string) error {
61 v.encoder = jsonEncoder()
63 v.encoder = consoleEncoder()
65 return fmt.Errorf("unknown encoder \"%s\"", e)
71 func (v encoderValue) String() string {
75 func (v encoderValue) Type() string {
79 func jsonEncoder() zapcore.Encoder {
80 encoderConfig := zap.NewProductionEncoderConfig()
81 return zapcore.NewJSONEncoder(encoderConfig)
84 func consoleEncoder() zapcore.Encoder {
85 encoderConfig := zap.NewDevelopmentEncoderConfig()
86 return zapcore.NewConsoleEncoder(encoderConfig)
89 type levelValue struct {
94 func (v *levelValue) Set(l string) error {
96 lower := strings.ToLower(l)
106 i, err := strconv.Atoi(lower)
108 return fmt.Errorf("invalid log level \"%s\"", l)
114 return fmt.Errorf("invalid log level \"%s\"", l)
117 v.level = zapcore.Level(int8(lvl))
118 // If log level is greater than debug, set glog/klog level to that level.
120 fs := flag.NewFlagSet("", flag.ContinueOnError)
122 err := fs.Set("v", fmt.Sprintf("%v", -1*lvl))
130 func (v levelValue) String() string {
131 return v.level.String()
134 func (v levelValue) Type() string {
138 type sampleValue struct {
143 func (v *sampleValue) Set(s string) error {
146 v.sample, err = strconv.ParseBool(s)
150 func (v sampleValue) String() string {
151 return strconv.FormatBool(v.sample)
154 func (v sampleValue) IsBoolFlag() bool {
158 func (v sampleValue) Type() string {