teelogger: make writes to /dev/console non-blocking

fixes https://github.com/rtr7/router7/issues/68
This commit is contained in:
Michael Stapelberg 2021-09-19 11:45:19 +02:00
parent a5a012dd96
commit e07002721d

View File

@ -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)
}