Last active
November 8, 2017 01:32
-
-
Save bketelsen/04363b53fa851277e25b7b243101003d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package log | |
type channelLogger struct { | |
subscribers []chan map[string]interface{} | |
} | |
// NewChannelLogger returns a Logger that sends log messages to subscribers | |
// as a map[string]interface{} | |
func NewChannelLogger() Logger { | |
cl := &channelLogger{ | |
subscribers: make([]chan map[string]interface{}, 0), | |
} | |
return cl | |
} | |
func (l *channelLogger) Log(keyvals ...interface{}) error { | |
n := (len(keyvals) + 1) / 2 // +1 to handle case when len is odd | |
m := make(map[string]interface{}, n) | |
for i := 0; i < len(keyvals); i += 2 { | |
k := keyvals[i] | |
var v interface{} = ErrMissingValue | |
if i+1 < len(keyvals) { | |
v = keyvals[i+1] | |
} | |
merge(m, k, v) | |
} | |
for _, s := range l.subscribers { | |
s := s // capture s for anonymous func closure | |
//clearly not safe to send if channel send blocks | |
// send in goroutine so it doesn't block here | |
// think of better solution tomorrow like wrapping in | |
// a timeout so we don't leak goroutines on blocking sends | |
// maybe the timeout is configurable and defaulted in the | |
// channelLogger struct? | |
go func() { | |
s <- m | |
}() | |
} | |
return nil | |
} | |
func (l *channelLogger) Subscribe(s chan map[string]interface{}) { | |
l.subscribers = append(l.subscribers, s) | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment