Skip to content

Commit 6f99060

Browse files
committedOct 11, 2019
Add LogToStderr, a programatic way to log exclusively to stderr or not
1 parent ab80cd2 commit 6f99060

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed
 

‎klog.go

+8
Original file line numberDiff line numberDiff line change
@@ -803,6 +803,14 @@ func SetOutputBySeverity(name string, w io.Writer) {
803803
logging.file[sev] = rb
804804
}
805805

806+
// LogToStderr sets whether to log exclusively to stderr, bypassing outputs
807+
func LogToStderr(stderr bool) {
808+
logging.mu.Lock()
809+
defer logging.mu.Unlock()
810+
811+
logging.toStderr = stderr
812+
}
813+
806814
// output writes the data to the log files and releases the buffer.
807815
func (l *loggingT) output(s severity, log logr.InfoLogger, buf *buffer, file string, line int, alsoToStderr bool) {
808816
l.mu.Lock()

‎klog_test.go

+15
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,21 @@ func TestSetOutputDataRace(t *testing.T) {
351351
}
352352
}
353353

354+
func TestLogToOutput(t *testing.T) {
355+
logging.toStderr = true
356+
defer logging.swap(logging.newBuffers())
357+
buf := new(bytes.Buffer)
358+
SetOutput(buf)
359+
LogToStderr(false)
360+
361+
Info("Does logging to an output work?")
362+
363+
str := buf.String()
364+
if !strings.Contains(str, "Does logging to an output work?") {
365+
t.Fatalf("Expected %q to contain \"Does logging to an output work?\"", str)
366+
}
367+
}
368+
354369
// vGlobs are patterns that match/don't match this file at V=2.
355370
var vGlobs = map[string]bool{
356371
// Easy to test the numeric match here.

0 commit comments

Comments
 (0)
Please sign in to comment.