Skip to content

Commit

Permalink
ktesting: capture log entries only if requested
Browse files Browse the repository at this point in the history
Most users won't need this feature. It was enabled by default to keep the API
simple and because the primary goal was unit testing, but benchmarks also need
this and there unnecessary overhead needs to be avoided.
  • Loading branch information
pohly committed Feb 2, 2023
1 parent 8b4cfd2 commit 80d8fa3
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion ktesting/example_test.go
Expand Up @@ -25,7 +25,7 @@ import (
)

func ExampleUnderlier() {
logger := ktesting.NewLogger(ktesting.NopTL{}, ktesting.NewConfig(ktesting.Verbosity(4)))
logger := ktesting.NewLogger(ktesting.NopTL{}, ktesting.NewConfig(ktesting.Verbosity(4), ktesting.BufferLogs(true)))

logger.Error(errors.New("failure"), "I failed", "what", "something")
logger.WithValues("request", 42).WithValues("anotherValue", "fish").Info("hello world")
Expand Down
16 changes: 16 additions & 0 deletions ktesting/options.go
Expand Up @@ -50,6 +50,7 @@ type configOptions struct {
verbosityFlagName string
vmoduleFlagName string
verbosityDefault int
bufferLogs bool
}

// VerbosityFlagName overrides the default -testing.v for the verbosity level.
Expand Down Expand Up @@ -94,6 +95,21 @@ func Verbosity(level int) ConfigOption {
}
}

// BufferLogs controlls whether log entries are captured in memory in addition
// to being printed. Off by default. Unit tests that want to verify that
// log entries are emitted as expected can turn this on and then retrieve
// the captured log through the Underlier LogSink interface.
//
// # Experimental
//
// Notice: This function is EXPERIMENTAL and may be changed or removed in a
// later release.
func BufferLogs(enabled bool) ConfigOption {
return func(co *configOptions) {
co.bufferLogs = enabled
}
}

// NewConfig returns a configuration with recommended defaults and optional
// modifications. Command line flags are not bound to any FlagSet yet.
//
Expand Down
4 changes: 4 additions & 0 deletions ktesting/testinglogger.go
Expand Up @@ -376,6 +376,10 @@ func (l tlogger) log(what LogType, msg string, level int, buf *buffer.Buffer, er
l.shared.buffer.text.WriteByte('\n')
}

if !l.shared.config.co.bufferLogs {
return
}

// Store as raw data.
l.shared.buffer.log = append(l.shared.buffer.log,
LogEntry{
Expand Down

0 comments on commit 80d8fa3

Please sign in to comment.