Skip to content

Commit

Permalink
runtime/logger: properly encode "trace" log-level
Browse files Browse the repository at this point in the history
This ensures that the loglevel for trace (and below), is logged as
"trace" instead of "level(-2)".

Signed-off-by: Hidde Beydals <hidde@hhh.computer>
  • Loading branch information
hiddeco committed Dec 11, 2023
1 parent d3aa542 commit c746b91
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions runtime/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,14 @@ func NewLogger(opts Options) logr.Logger {

switch opts.LogEncoding {
case "console":
zapOpts.EncoderConfigOptions = append(zapOpts.EncoderConfigOptions, func(config *zapcore.EncoderConfig) {
config.EncodeLevel = CapitalLevelEncoder
})
zap.ConsoleEncoder(zapOpts.EncoderConfigOptions...)(&zapOpts)
case "json":
zapOpts.EncoderConfigOptions = append(zapOpts.EncoderConfigOptions, func(config *zapcore.EncoderConfig) {
config.EncodeLevel = LowercaseLevelEncoder
})
zap.JSONEncoder(zapOpts.EncoderConfigOptions...)(&zapOpts)
}

Expand All @@ -121,3 +127,25 @@ func SetLogger(logger logr.Logger) {
ctrl.SetLogger(logger)
klog.SetLoggerWithOptions(logger.WithName("runtime"), klog.ContextualLogger(true))
}

// LowercaseLevelEncoder is a zapcore.LevelEncoder that encodes the level to a lowercase string.
// It has the same behavior as zapcore.LowercaseLevelEncoder, except that it has a special case
// for the trace level, which it encodes as "trace" instead of "Level(-2)".
func LowercaseLevelEncoder(l zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
if l < zapcore.DebugLevel {
enc.AppendString("trace")
return
}
zapcore.LowercaseLevelEncoder(l, enc)
}

// CapitalLevelEncoder is a zapcore.LevelEncoder that encodes the level to a capitalized string.
// It has the same behavior as zapcore.CapitalLevelEncoder, except that it encodes the trace
// level as "TRACE" instead of "LEVEL(-2)".
func CapitalLevelEncoder(l zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
if l < zapcore.DebugLevel {
enc.AppendString("TRACE")
return
}
zapcore.CapitalLevelEncoder(l, enc)
}

0 comments on commit c746b91

Please sign in to comment.