Skip to content

Commit

Permalink
Handle error returned by std.flush()
Browse files Browse the repository at this point in the history
Also handle error returned by closing $TMPDIR/q file.
  • Loading branch information
ryboe authored and Ryan Boehning committed May 26, 2018
1 parent 341b9bb commit cb1faea
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions q.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,17 +96,25 @@ func (l *logger) resetTimer(d time.Duration) (expired bool) {
}

// flush writes the logger's buffer to disk.
func (l *logger) flush() error {
func (l *logger) flush() (err error) {
path := filepath.Join(os.TempDir(), "q")
f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return fmt.Errorf("failed to open %q: %v", path, err)
}
defer f.Close()
defer func() {
if cerr := f.Close(); err == nil {
err = cerr
}
}()

_, err = io.Copy(f, l.buf)
l.buf.Reset()
return fmt.Errorf("failed to flush q buffer: %v", err)
if err != nil {
return fmt.Errorf("failed to flush q buffer: %v", err)
}

return nil
}

// output writes to the log buffer. Each log message is prepended with a
Expand Down Expand Up @@ -154,7 +162,11 @@ func Q(v ...interface{}) {
defer std.mu.Unlock()

// Flush the buffered writes to disk.
defer std.flush()
defer func() {
if err := std.flush(); err != nil {
fmt.Println(err)
}
}()

args := formatArgs(v...)
funcName, file, line, err := getCallerInfo()
Expand Down

0 comments on commit cb1faea

Please sign in to comment.