Total Lines | 67 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | //////////////////////////////////////////////////////////////////////////////// |
||
7 | package alog |
||
8 | |||
9 | import ( |
||
10 | "errors" |
||
11 | "fmt" |
||
12 | "io" |
||
13 | "log" |
||
14 | ) |
||
15 | |||
16 | // Logger types |
||
17 | const ( |
||
18 | Info uint = iota |
||
19 | Wrn |
||
20 | Err |
||
21 | ) |
||
22 | |||
23 | // Logger logger structure which includes a channel and a slice strategies |
||
24 | type Logger struct { |
||
25 | io.Writer |
||
26 | Channel chan string |
||
27 | Strategies []io.Writer |
||
28 | } |
||
29 | |||
30 | // Map mapping for type:logger |
||
31 | type Map map[uint]*Logger |
||
32 | |||
33 | var loggerName = map[uint]string{ |
||
34 | Info: "Info", |
||
35 | Wrn: "Warning", |
||
36 | Err: "Error", |
||
37 | } |
||
38 | |||
39 | // Name returns a name for the logger. |
||
40 | // It returns the empty string if the code is unknown. |
||
41 | func Name(code uint) string { |
||
42 | return loggerName[code] |
||
43 | } |
||
44 | |||
45 | // Writer interface for informational messages |
||
46 | func (l *Logger) Write(p []byte) (n int, err error) { |
||
47 | if l == nil || isClosedCh(l.Channel) { |
||
48 | return 0, errors.New("the channel was closed for recording") |
||
49 | } |
||
50 | l.Channel <- string(p) |
||
51 | return len(p), nil |
||
52 | } |
||
53 | |||
54 | func isClosedCh(ch <-chan string) bool { |
||
55 | select { |
||
56 | case <-ch: |
||
57 | return true |
||
58 | default: |
||
59 | return false |
||
60 | } |
||
61 | } |
||
62 | |||
63 | //Reader for messages |
||
64 | func (l *Logger) Reader() { |
||
65 | for msg := range l.Channel { |
||
66 | l.writeMessage(msg) |
||
67 | } |
||
68 | } |
||
69 | |||
70 | func (l *Logger) writeMessage(msg string) { |
||
71 | for _, s := range l.Strategies { |
||
72 | if n, err := s.Write([]byte(msg)); err != nil { |
||
73 | log.Println(fmt.Sprintf("%d characters have been written. %s", n, err.Error())) |
||
74 | } |
||
77 |