Skip to content

Commit

Permalink
Write to list of writers, flush if possible
Browse files Browse the repository at this point in the history
  • Loading branch information
bobheadxi committed Jun 1, 2018
1 parent 904d9f5 commit 717b328
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 20 deletions.
8 changes: 6 additions & 2 deletions daemon/inertiad/log/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,14 @@ func NewLogger(opts LoggerOptions) *DaemonLogger {
var w io.Writer
if !opts.HTTPStream {
// Attempt to create a writer with websocket
w = &TwoWriter{opts.Stdout, NewWebSocketTextWriter(opts.Socket)}
w = &MultiWriter{
writers: []io.Writer{opts.Stdout, NewWebSocketTextWriter(opts.Socket)},
}
} else {
// Attempt to create a writer with HTTPWriter
w = &TwoWriter{opts.Stdout, opts.HTTPWriter}
w = &MultiWriter{
writers: []io.Writer{opts.Stdout, opts.HTTPWriter},
}
}

return &DaemonLogger{
Expand Down
40 changes: 22 additions & 18 deletions daemon/inertiad/log/writers.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package log

import (
"io"
"net/http"

"github.com/gorilla/websocket"
)
Expand Down Expand Up @@ -33,27 +34,30 @@ func NewWebSocketTextWriter(socket SocketWriter) *WebSocketWriter {
}
}

// TwoWriter writes to two writers without caring whether one fails
type TwoWriter struct {
writer1 io.Writer
writer2 io.Writer
// MultiWriter writes to list of writers without caring whether one fails, and
// flushes if writer is flushable
type MultiWriter struct {
writers []io.Writer
}

func (t *TwoWriter) Write(p []byte) (int, error) {
func (m *MultiWriter) Write(p []byte) (int, error) {
var (
len1 int
len2 int
err1 error
err2 error
lastLen int
lastErr error
)
if t.writer1 != nil {
len1, err1 = t.writer1.Write(p)
for _, writer := range m.writers {
if writer == nil {
continue
}
len, err := writer.Write(p)
if err != nil {
lastErr = err
} else {
lastLen = len
if f, ok := writer.(http.Flusher); ok {
f.Flush()
}
}
}
if t.writer2 != nil {
len2, err2 = t.writer2.Write(p)
}
if err1 != nil {
return len1, err1
}
return len2, err2
return lastLen, lastErr
}

0 comments on commit 717b328

Please sign in to comment.