2016-11-04 04:14:56 +00:00
|
|
|
package logger
|
2013-12-21 00:39:32 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
// LogHandler interface is used for clients that want to subscribe
|
|
|
|
// to logs, for example to stream them over an IPC mechanism
|
|
|
|
type LogHandler interface {
|
|
|
|
HandleLog(string)
|
|
|
|
}
|
|
|
|
|
2016-11-04 04:14:56 +00:00
|
|
|
// LogWriter implements io.Writer so it can be used as a log sink.
|
2013-12-21 00:39:32 +00:00
|
|
|
// It maintains a circular buffer of logs, and a set of handlers to
|
|
|
|
// which it can stream the logs to.
|
2016-11-04 04:14:56 +00:00
|
|
|
type LogWriter struct {
|
2013-12-21 00:39:32 +00:00
|
|
|
sync.Mutex
|
|
|
|
logs []string
|
|
|
|
index int
|
|
|
|
handlers map[LogHandler]struct{}
|
|
|
|
}
|
|
|
|
|
2016-11-04 04:14:56 +00:00
|
|
|
// NewLogWriter creates a LogWriter with the given buffer capacity
|
|
|
|
func NewLogWriter(buf int) *LogWriter {
|
|
|
|
return &LogWriter{
|
2013-12-21 00:39:32 +00:00
|
|
|
logs: make([]string, buf),
|
|
|
|
index: 0,
|
|
|
|
handlers: make(map[LogHandler]struct{}),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-12-04 23:25:06 +00:00
|
|
|
// RegisterHandler adds a log handler to receive logs, and sends
|
2013-12-21 00:39:32 +00:00
|
|
|
// the last buffered logs to the handler
|
2016-11-04 04:14:56 +00:00
|
|
|
func (l *LogWriter) RegisterHandler(lh LogHandler) {
|
2013-12-21 00:39:32 +00:00
|
|
|
l.Lock()
|
|
|
|
defer l.Unlock()
|
|
|
|
|
|
|
|
// Do nothing if already registered
|
|
|
|
if _, ok := l.handlers[lh]; ok {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Register
|
|
|
|
l.handlers[lh] = struct{}{}
|
|
|
|
|
|
|
|
// Send the old logs
|
|
|
|
if l.logs[l.index] != "" {
|
|
|
|
for i := l.index; i < len(l.logs); i++ {
|
|
|
|
lh.HandleLog(l.logs[i])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for i := 0; i < l.index; i++ {
|
|
|
|
lh.HandleLog(l.logs[i])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// DeregisterHandler removes a LogHandler and prevents more invocations
|
2016-11-04 04:14:56 +00:00
|
|
|
func (l *LogWriter) DeregisterHandler(lh LogHandler) {
|
2013-12-21 00:39:32 +00:00
|
|
|
l.Lock()
|
|
|
|
defer l.Unlock()
|
|
|
|
delete(l.handlers, lh)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write is used to accumulate new logs
|
2016-11-04 04:14:56 +00:00
|
|
|
func (l *LogWriter) Write(p []byte) (n int, err error) {
|
2013-12-21 00:39:32 +00:00
|
|
|
l.Lock()
|
|
|
|
defer l.Unlock()
|
|
|
|
|
|
|
|
// Strip off newlines at the end if there are any since we store
|
|
|
|
// individual log lines in the agent.
|
|
|
|
n = len(p)
|
|
|
|
if p[n-1] == '\n' {
|
|
|
|
p = p[:n-1]
|
|
|
|
}
|
|
|
|
|
|
|
|
l.logs[l.index] = string(p)
|
|
|
|
l.index = (l.index + 1) % len(l.logs)
|
|
|
|
|
|
|
|
for lh, _ := range l.handlers {
|
|
|
|
lh.HandleLog(string(p))
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|