Switch to go.uber.org/zap for JSON formatted logging

Signed-off-by: Monis Khan <mok@vmware.com>
This commit is contained in:
Monis Khan
2022-04-15 22:43:53 -04:00
parent 03ccef03fe
commit 0674215ef3
63 changed files with 2033 additions and 470 deletions

View File

@@ -4,18 +4,18 @@
package plog
import (
"strconv"
"k8s.io/component-base/logs"
"go.uber.org/zap/zapcore"
"k8s.io/klog/v2"
"go.pinniped.dev/internal/constable"
)
// LogLevel is an enum that controls verbosity of logs.
// Valid values in order of increasing verbosity are leaving it unset, info, debug, trace and all.
type LogLevel string
func (l LogLevel) Enabled(_ zapcore.Level) bool {
return Enabled(l) // this basically says "log if the global plog level is l or greater"
}
const (
// LevelWarning (i.e. leaving the log level unset) maps to klog log level 0.
LevelWarning LogLevel = ""
@@ -27,33 +27,40 @@ const (
LevelTrace LogLevel = "trace"
// LevelAll maps to klog log level 100 (conceptually it is log level 8).
LevelAll LogLevel = "all"
errInvalidLogLevel = constable.Error("invalid log level, valid choices are the empty string, info, debug, trace and all")
)
var _ zapcore.LevelEnabler = LevelWarning
const (
klogLevelWarning = iota * 2
klogLevelInfo
klogLevelDebug
klogLevelTrace
KlogLevelInfo
KlogLevelDebug
KlogLevelTrace
klogLevelAll
)
func ValidateAndSetLogLevelGlobally(level LogLevel) error {
klogLevel := klogLevelForPlogLevel(level)
if klogLevel < 0 {
return errInvalidLogLevel
}
if _, err := logs.GlogSetter(strconv.Itoa(int(klogLevel))); err != nil {
panic(err) // programmer error
}
return nil
}
// Enabled returns whether the provided plog level is enabled, i.e., whether print statements at the
// provided level will show up.
func Enabled(level LogLevel) bool {
return klog.V(klogLevelForPlogLevel(level)).Enabled()
l := klogLevelForPlogLevel(level)
// check that both our global level and the klog global level agree that the plog level is enabled
// klog levels are inverted when zap handles them
return globalLevel.Enabled(zapcore.Level(-l)) && klog.V(l).Enabled()
}
func klogLevelForPlogLevel(plogLevel LogLevel) klog.Level {
switch plogLevel {
case LevelWarning:
return klogLevelWarning // unset means minimal logs (Error and Warning)
case LevelInfo:
return KlogLevelInfo
case LevelDebug:
return KlogLevelDebug
case LevelTrace:
return KlogLevelTrace
case LevelAll:
return klogLevelAll + 100 // make all really mean all
default:
return -1
}
}