logger.go   A
last analyzed

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 38
dl 0
loc 67
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A alog.*Logger.Write 0 6 3
A alog.isClosedCh 0 6 3
A alog.*Logger.Reader 0 3 2
A alog.Name 0 2 1
A alog.*Logger.writeMessage 0 4 3
1
////////////////////////////////////////////////////////////////////////////////
2
// Author:   Nikita Koryabkin
3
// Email:    [email protected]
4
// Telegram: https://t.me/Apologiz
5
////////////////////////////////////////////////////////////////////////////////
6
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
		}
75
	}
76
}
77