Skip to content

Commit

Permalink
Add LogToOutput, a one-stop shop for writing logs to a io.Writer
Browse files Browse the repository at this point in the history
  • Loading branch information
liztio committed Oct 10, 2019
1 parent ab80cd2 commit 9e1b271
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
10 changes: 10 additions & 0 deletions klog.go
Expand Up @@ -803,6 +803,16 @@ func SetOutputBySeverity(name string, w io.Writer) {
logging.file[sev] = rb
}

// LogToOutput configures klog to output to the specified writer. It is equivalent to SetOutput()
// and flag.Set("logtostderr", "false")
func LogToOutput(w io.Writer) {
SetOutput(w)
logging.mu.Lock()
defer logging.mu.Unlock()

logging.toStderr = false
}

// 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()
Expand Down
13 changes: 13 additions & 0 deletions klog_test.go
Expand Up @@ -351,6 +351,19 @@ func TestSetOutputDataRace(t *testing.T) {
}
}

func TestLogToOutput(t *testing.T) {
defer logging.swap(logging.newBuffers())
buf := new(bytes.Buffer)
LogToOutput(buf)

Info("Does LogToOutput work?")

str := buf.String()
if !strings.Contains(str, "Does LogToOutput work?") {
t.Fatalf("Expected %s to contain \"Does LogToOutput 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.
Expand Down

0 comments on commit 9e1b271

Please sign in to comment.