teelogger: make writes to /dev/console non-blocking
fixes https://github.com/rtr7/router7/issues/68
This commit is contained in:
parent
a5a012dd96
commit
e07002721d
@ -23,12 +23,36 @@ import (
|
|||||||
"os"
|
"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 {
|
func NewConsole() *log.Logger {
|
||||||
var w io.Writer
|
w := ioutil.Discard
|
||||||
w, err := os.OpenFile("/dev/console", os.O_RDWR, 0600)
|
if console, err := os.OpenFile("/dev/console", os.O_RDWR, 0600); err == nil {
|
||||||
if err != nil {
|
ch := make(chan string, 1)
|
||||||
w = ioutil.Discard
|
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)
|
return log.New(io.MultiWriter(os.Stderr, w), "", log.LstdFlags|log.Lshortfile)
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user