Skip to content

Commit c4b9e86

Browse files
authored
Developer productivity: make klog configurable (#2356)
* make klog configurable * address linter
1 parent 6f99b9c commit c4b9e86

File tree

2 files changed

+91
-5
lines changed

2 files changed

+91
-5
lines changed

cmd/main.go

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"fmt"
2121
"log"
2222
"os"
23+
"strconv"
2324
"strings"
2425
"time"
2526

@@ -68,8 +69,9 @@ func main() {
6869
os.Exit(1)
6970
}
7071

71-
ctrl.SetLogger(zapr.NewLogger(logger))
72-
klog.SetLogger(zapr.NewLogger(logger))
72+
logrLogger := zapr.NewLogger(logger)
73+
ctrl.SetLogger(logrLogger.WithName("ctrl"))
74+
klog.SetLogger(logrLogger.WithName("klog"))
7375
setupLog := logger.Named("setup").Sugar()
7476
setupLog.Info("starting with configuration", zap.Any("config", config), zap.Any("version", version.Version))
7577

@@ -127,7 +129,7 @@ func parseConfiguration() Config {
127129
flag.BoolVar(&config.EnableLeaderElection, "leader-elect", false,
128130
"Enable leader election for controller manager. "+
129131
"Enabling this will ensure there is only one active controller manager.")
130-
flag.StringVar(&config.LogLevel, "log-level", "info", "Log level. Available values: debug | info | warn | error | dpanic | panic | fatal")
132+
flag.StringVar(&config.LogLevel, "log-level", "info", "Log level. Available values: debug | info | warn | error | dpanic | panic | fatal or a numeric value from -9 to 5, where -9 is the most verbose and 5 is the least verbose.")
131133
flag.StringVar(&config.LogEncoder, "log-encoder", "json", "Log encoder. Available values: json | console")
132134
flag.BoolVar(&config.ObjectDeletionProtection, objectDeletionProtectionFlag, objectDeletionProtectionDefault, "Defines if the operator deletes Atlas resource "+
133135
"when a Custom Resource is deleted")
@@ -191,9 +193,32 @@ func operatorGlobalKeySecretOrDefault(secretNameOverride string) client.ObjectKe
191193

192194
func initCustomZapLogger(level, encoding string) (*zap.Logger, error) {
193195
lv := zap.AtomicLevel{}
194-
err := lv.UnmarshalText([]byte(strings.ToLower(level)))
196+
197+
i64, err := strconv.ParseInt(level, 10, 8)
198+
numericLevel := int8(i64)
195199
if err != nil {
196-
return nil, err
200+
// not a numeric level, try to unmarshal it as a zapcore.Level ("debug", "info", "warn", "error", "dpanic", "panic", or "fatal")
201+
err := lv.UnmarshalText([]byte(strings.ToLower(level)))
202+
if err != nil {
203+
return nil, err
204+
}
205+
} else {
206+
// numeric level:
207+
// 1. configure klog if the numeric log level is negative and the absolute value of the negative numeric value represents the klog level.
208+
// 2. configure the atomic zap level based on the numeric value (5..-9).
209+
210+
var klogLevel int8 = 0
211+
if numericLevel < 0 {
212+
klogLevel = -numericLevel
213+
}
214+
215+
klogFlagSet := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
216+
klog.InitFlags(klogFlagSet)
217+
if err := klogFlagSet.Set("v", strconv.Itoa(int(klogLevel))); err != nil {
218+
return nil, err
219+
}
220+
221+
lv = zap.NewAtomicLevelAt(zapcore.Level(numericLevel))
197222
}
198223

199224
enc := strings.ToLower(encoding)

cmd/main_test.go

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"testing"
2121

2222
"github.com/stretchr/testify/assert"
23+
"go.uber.org/zap/zapcore"
2324
)
2425

2526
func Test_configureDeletionProtection(t *testing.T) {
@@ -194,3 +195,63 @@ func Test_configureDeletionProtection(t *testing.T) {
194195
)
195196
})
196197
}
198+
199+
func TestInitCustomZapLogger(t *testing.T) {
200+
tests := []struct {
201+
name string
202+
level string
203+
wantLevel zapcore.Level
204+
wantErr bool
205+
}{
206+
{
207+
name: "valid string level info with json encoding",
208+
level: "info",
209+
wantLevel: zapcore.InfoLevel,
210+
wantErr: false,
211+
},
212+
{
213+
name: "valid string level debug with console encoding",
214+
level: "debug",
215+
wantLevel: zapcore.DebugLevel,
216+
wantErr: false,
217+
},
218+
{
219+
name: "valid numeric level",
220+
level: "-1",
221+
wantLevel: zapcore.Level(-1),
222+
wantErr: false,
223+
},
224+
{
225+
name: "valid numeric level",
226+
level: "-255",
227+
wantErr: true,
228+
},
229+
{
230+
name: "invalid level",
231+
level: "invalid",
232+
wantErr: true,
233+
},
234+
}
235+
236+
for _, tt := range tests {
237+
t.Run(tt.name, func(t *testing.T) {
238+
logger, err := initCustomZapLogger(tt.level, "json")
239+
240+
if tt.wantErr {
241+
assert.Error(t, err)
242+
assert.Nil(t, logger)
243+
return
244+
}
245+
246+
assert.NoError(t, err)
247+
assert.NotNil(t, logger)
248+
249+
if logger == nil {
250+
return
251+
}
252+
// Verify logger configuration
253+
loggerImpl := logger.Core()
254+
assert.True(t, loggerImpl.Enabled(tt.wantLevel))
255+
})
256+
}
257+
}

0 commit comments

Comments
 (0)