-
Notifications
You must be signed in to change notification settings - Fork 0
/
streammanager.go
66 lines (56 loc) · 1.84 KB
/
streammanager.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package gonyan
import (
"fmt"
)
// StreamManager wraps up all supported stream types.
type StreamManager struct {
streams map[LogLevel][]Stream
}
// NewStreamManager creates a new, properly initialised,
// StreamManager instance.
func NewStreamManager() *StreamManager {
s := &StreamManager{}
s.streams = make(map[LogLevel][]Stream)
s.streams[Debug] = make([]Stream, 0)
s.streams[Verbose] = make([]Stream, 0)
s.streams[Info] = make([]Stream, 0)
s.streams[Warning] = make([]Stream, 0)
s.streams[Error] = make([]Stream, 0)
s.streams[Fatal] = make([]Stream, 0)
s.streams[Panic] = make([]Stream, 0)
return s
}
// Register internally saves provided stream into proper stream container.
func (s *StreamManager) Register(level LogLevel, stream Stream) error {
registeredStreams, ok := s.streams[level]
if !ok {
return fmt.Errorf("invalid log level provided")
}
registeredStreams = append(registeredStreams, stream)
s.streams[level] = registeredStreams
return nil
}
// Send function fires stream writes operations for provided LogMessage
// into all streams registered from provided LogLevel.
//
// Note: all Write invocations are performed synchronously to avoid spawning
// too much go-routines, the Stream is in charge of implementing asynchronous
// mechanisms to avoid waiting too much on a log operation.
// This might change in the future depending on how the package itself grows.
func (s *StreamManager) Send(level LogLevel, message *LogMessage) error {
if message == nil {
return fmt.Errorf("invalid nil message")
}
registeredStreams, ok := s.streams[level]
if !ok {
return fmt.Errorf("invalid log level provided")
}
messageBytes, err := message.Serialise()
if err != nil {
return fmt.Errorf("serialisation error: %s", err.Error())
}
for i := 0; i < len(registeredStreams); i++ {
registeredStreams[i].Write(messageBytes)
}
return nil
}