From 6f990606b8038ad35648cb1a405d80b75fe06b49 Mon Sep 17 00:00:00 2001 From: liz Date: Wed, 9 Oct 2019 15:37:41 -0400 Subject: [PATCH] Add LogToStderr, a programatic way to log exclusively to stderr or not --- klog.go | 8 ++++++++ klog_test.go | 15 +++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/klog.go b/klog.go index 4eff736e..765893fa 100644 --- a/klog.go +++ b/klog.go @@ -803,6 +803,14 @@ func SetOutputBySeverity(name string, w io.Writer) { logging.file[sev] = rb } +// LogToStderr sets whether to log exclusively to stderr, bypassing outputs +func LogToStderr(stderr bool) { + logging.mu.Lock() + defer logging.mu.Unlock() + + logging.toStderr = stderr +} + // output writes the data to the log files and releases the buffer. func (l *loggingT) output(s severity, log logr.InfoLogger, buf *buffer, file string, line int, alsoToStderr bool) { l.mu.Lock() diff --git a/klog_test.go b/klog_test.go index fae5a2f7..e7a5608d 100644 --- a/klog_test.go +++ b/klog_test.go @@ -351,6 +351,21 @@ func TestSetOutputDataRace(t *testing.T) { } } +func TestLogToOutput(t *testing.T) { + logging.toStderr = true + defer logging.swap(logging.newBuffers()) + buf := new(bytes.Buffer) + SetOutput(buf) + LogToStderr(false) + + Info("Does logging to an output work?") + + str := buf.String() + if !strings.Contains(str, "Does logging to an output work?") { + t.Fatalf("Expected %q to contain \"Does logging to an output work?\"", str) + } +} + // vGlobs are patterns that match/don't match this file at V=2. var vGlobs = map[string]bool{ // Easy to test the numeric match here.