diff --git a/internal/teelogger/teelogger.go b/internal/teelogger/teelogger.go index 0facdb6..208aa53 100644 --- a/internal/teelogger/teelogger.go +++ b/internal/teelogger/teelogger.go @@ -23,12 +23,36 @@ import ( "os" ) -// NewConsole returns a logger which returns to /dev/console and os.Stderr. +type nonBlockingWriter struct { + W chan<- string +} + +func (w *nonBlockingWriter) Write(p []byte) (n int, _ error) { + select { + // Intentionally convert from byte slice ([]byte) to string because sending + // a byte slice over a channel is not safe: it may point to new contents, + // resulting in duplicate log lines showing up. + case w.W <- string(p): + default: + // channel unavailable, ignore + } + return len(p), nil +} + +// NewConsole returns a logger which returns to /dev/console and +// os.Stderr. Writes to /dev/console are non-blocking, i.e. messages will be +// discarded if /dev/console stalls (e.g. when enabling Scroll Lock on a HDMI +// console). func NewConsole() *log.Logger { - var w io.Writer - w, err := os.OpenFile("/dev/console", os.O_RDWR, 0600) - if err != nil { - w = ioutil.Discard + w := ioutil.Discard + if console, err := os.OpenFile("/dev/console", os.O_RDWR, 0600); err == nil { + ch := make(chan string, 1) + go func() { + for buf := range ch { + console.Write([]byte(buf)) + } + }() + w = &nonBlockingWriter{W: ch} } return log.New(io.MultiWriter(os.Stderr, w), "", log.LstdFlags|log.Lshortfile) }