Skip to content

Commit

Permalink
Fix 100% cpu util when tailing file
Browse files Browse the repository at this point in the history
If the file could not be read or tail had an error, the process
would spin in a look pegging a CPU.
  • Loading branch information
jwilder committed Mar 17, 2018
1 parent 8ed4b77 commit 4c86ed7
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions tail.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,31 @@ func tailFile(ctx context.Context, file string, poll bool, dest *os.File) {
Logger: tail.DiscardingLogger,
})
if err != nil {
log.Fatalf("unable to tail %s: %s", "foo", err)
log.Fatalf("unable to tail %s: %s", file, err)
}

defer func() {
t.Stop()
t.Cleanup()
}()

// main loop
for {
select {
// if the channel is done, then exit the loop
case <-ctx.Done():
t.Stop()
t.Cleanup()
return
// get the next log line and echo it out
case line := <-t.Lines:
if line != nil {
fmt.Fprintln(dest, line.Text)
if line == nil {
if t.Err() != nil {
log.Fatalf("unable to tail %s: %s", file, t.Err())
}
return
} else if line.Err != nil {
log.Fatalf("unable to tail %s: %s", file, t.Err())
}
fmt.Fprintln(dest, line.Text)
}
}
}

0 comments on commit 4c86ed7

Please sign in to comment.