Skip to content

Commit

Permalink
glog: use os.Stderr directly for writing to stderr (#62)
Browse files Browse the repository at this point in the history
This was raised in https://groups.google.com/g/golang-nuts/c/o85vycfiGVY/m/MblpnfF6BQAJ.

Before the 1.1.0 release it was possible to set os.Stderr to a different *os.File (like an os.Pipe) to capture output that is written to stderr. Restore that behavior.
  • Loading branch information
chressie authored Mar 22, 2023
1 parent 6ce8ac9 commit 03ad3c2
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions glog_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,6 @@ var sinks struct {
}

func init() {
sinks.stderr.w = os.Stderr

// Register stderr first: that way if we crash during file-writing at least
// the log will have gone somewhere.
logsink.TextSinks = append(logsink.TextSinks, &sinks.stderr, &sinks.file)
Expand All @@ -167,7 +165,7 @@ func init() {
// if they meet certain conditions.
type stderrSink struct {
mu sync.Mutex
w io.Writer
w io.Writer // if nil Emit uses os.Stderr directly
}

// Enabled implements logsink.Text.Enabled. It returns true if any of the
Expand All @@ -182,8 +180,11 @@ func (s *stderrSink) Enabled(m *logsink.Meta) bool {
func (s *stderrSink) Emit(m *logsink.Meta, data []byte) (n int, err error) {
s.mu.Lock()
defer s.mu.Unlock()

dn, err := s.w.Write(data)
w := s.w
if w == nil {
w = os.Stderr
}
dn, err := w.Write(data)
n += dn
return n, err
}
Expand Down

0 comments on commit 03ad3c2

Please # to comment.