logger.*Logger.Fatalf   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
dl 0
loc 3
c 0
b 0
f 0
rs 10
nop 2
1
package logger
2
3
import (
4
	"errors"
5
	"fmt"
6
	"io"
7
	"os"
8
	"strings"
9
	"sync"
10
)
11
12
const (
13
	LevelError = iota
14
	LevelWarn
15
	LevelInfo
16
	LevelDebug
17
)
18
19
var ErrLogLevel = errors.New("unrecognized log_level")
20
21
type Conf struct {
22
	Level string `toml:"level"`
23
}
24
25
type Logger struct {
26
	level  int
27
	writer io.Writer
28
	mu     *sync.Mutex
29
}
30
31
func NewLogger(level string, writer io.Writer) *Logger {
32
	switch strings.ToUpper(level) {
33
	case "ERROR":
34
		return &Logger{level: LevelError, mu: &sync.Mutex{}, writer: writer}
35
	case "WARN":
36
		return &Logger{level: LevelWarn, mu: &sync.Mutex{}, writer: writer}
37
	case "INFO":
38
		return &Logger{level: LevelInfo, mu: &sync.Mutex{}, writer: writer}
39
	case "DEBUG":
40
		return &Logger{level: LevelDebug, mu: &sync.Mutex{}, writer: writer}
41
	default:
42
		fmt.Fprintln(os.Stderr, "unrecognized log_level")
43
		os.Exit(1)
44
	}
45
	return nil
46
}
47
48
func (l *Logger) printf(format string, a ...interface{}) {
49
	l.mu.Lock()
50
	_, err := fmt.Fprintf(l.writer, format, a...)
0 ignored issues
show
introduced by
can't check non-constant format in call to Fprintf
Loading history...
51
	l.mu.Unlock()
52
	if err != nil {
53
		fmt.Fprintf(os.Stderr, "Fatal: Fprintf : %v", err)
54
		os.Exit(1)
55
	}
56
}
57
58
func (l *Logger) Fatalf(format string, a ...interface{}) {
59
	l.printf("Fatal:"+format, a)
0 ignored issues
show
introduced by
can't check non-constant format in call to printf
Loading history...
60
	os.Exit(1)
61
}
62
63
func (l *Logger) Errorf(format string, a ...interface{}) {
64
	if l.level >= LevelError {
65
		l.printf("ERROR:"+format, a...)
0 ignored issues
show
introduced by
can't check non-constant format in call to printf
Loading history...
66
	}
67
}
68
69
func (l *Logger) Warningf(format string, a ...interface{}) {
70
	if l.level >= LevelWarn {
71
		l.printf("WARN:"+format, a...)
0 ignored issues
show
introduced by
can't check non-constant format in call to printf
Loading history...
72
	}
73
}
74
75
func (l *Logger) Infof(format string, a ...interface{}) {
76
	if l.level >= LevelInfo {
77
		l.printf("INFO:"+format, a...)
0 ignored issues
show
introduced by
can't check non-constant format in call to printf
Loading history...
78
	}
79
}
80
81
func (l *Logger) Debugf(format string, a ...interface{}) {
82
	if l.level >= LevelDebug {
83
		l.printf("DEBUG:"+format, a...)
0 ignored issues
show
introduced by
can't check non-constant format in call to printf
Loading history...
84
	}
85
}
86