trufflehog/pkg/log/core.go
Miccah f3367d7910
[THOG-643] Implement independent log level controls (#733)
* [THOG-643] Implement independent log level controls

There are two log level controls to mentally distinguish. Log levels
associated with a sink (e.g. stdout and streamed), and log levels
associated with a logger (e.g. a GitHub source).

The level is determined to be the minimum of the two. If a sink is at
level 0, then it will only output level 0 logs regardless of the
logger's level. This is best demonstrated by TestSinkWithName.

* Rename WithName to WithNamedLevel

* Check flush errors

* Replace IncreaseLevelCore with custom LevelCore

Adding a leveler that was less verbose would cause the initialization
fail, and therefore not be added to the core. This check is only at
the time of initialization.

An alternative approach to creating our own core is to set the child log
level equal to the parent, so initialization is guaranteed (with the
added benefit of intuitive behavior).

* Use controller if it exists, otherwise inherit parent's log level

* Cleanup some tests
2022-08-26 15:27:09 -05:00

41 lines
1 KiB
Go

package log
import (
"go.uber.org/zap/zapcore"
)
type levelFilterCore struct {
core zapcore.Core
level zapcore.LevelEnabler
}
// NewLevelCore creates a core that can be used to independently control the
// level of an existing Core. This is essentially a filter that will only log
// if both the parent and the wrapper cores are enabled.
func NewLevelCore(core zapcore.Core, level zapcore.LevelEnabler) zapcore.Core {
return &levelFilterCore{core, level}
}
func (c *levelFilterCore) Enabled(lvl zapcore.Level) bool {
return c.level.Enabled(lvl)
}
func (c *levelFilterCore) With(fields []zapcore.Field) zapcore.Core {
return &levelFilterCore{c.core.With(fields), c.level}
}
func (c *levelFilterCore) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
if !c.Enabled(ent.Level) {
return ce
}
return c.core.Check(ent, ce)
}
func (c *levelFilterCore) Write(ent zapcore.Entry, fields []zapcore.Field) error {
return c.core.Write(ent, fields)
}
func (c *levelFilterCore) Sync() error {
return c.core.Sync()
}