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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
package logger
import (
"fmt"
"log"
"os"
"sync"
)
const (
LevelDebug Level = iota + 1
LevelInfo
LevelNotice
LevelFatal
)
type Level int
func NewLevel(str string) (Level, error) {
switch str {
case LevelDebug.String():
return LevelDebug, nil
case LevelInfo.String():
return LevelInfo, nil
case LevelNotice.String():
return LevelNotice, nil
case LevelFatal.String():
return LevelFatal, nil
}
return Level(0), fmt.Errorf("unknown level %q", str)
}
func (lv Level) String() string {
switch lv {
case LevelDebug:
return "DEBUG"
case LevelInfo:
return "INFO"
case LevelNotice:
return "NOTICE"
case LevelFatal:
return "FATAL"
default:
return "UNKNOWN"
}
}
type Config struct {
Level Level
File *os.File
}
type Logger struct {
cfg Config
log log.Logger
mutex sync.Mutex
}
func New(cfg Config) *Logger {
l := Logger{}
l.Reconfigure(cfg)
return &l
}
func (l *Logger) Reconfigure(cfg Config) {
l.mutex.Lock()
defer l.mutex.Unlock()
if cfg.Level < LevelDebug || cfg.Level > LevelFatal {
cfg.Level = LevelNotice
}
if cfg.File == nil {
cfg.File = os.Stdout
}
l.cfg = cfg
l.log = *log.New(l.cfg.File, "", log.Ldate|log.Ltime)
}
func (l *Logger) IsConfigured() bool {
return l.cfg.File != nil
}
func (l *Logger) Debugf(format string, args ...interface{}) { l.printf(LevelDebug, format, args...) }
func (l *Logger) Infof(format string, args ...interface{}) { l.printf(LevelInfo, format, args...) }
func (l *Logger) Noticef(format string, args ...interface{}) { l.printf(LevelNotice, format, args...) }
func (l *Logger) Fatalf(format string, args ...interface{}) { l.printf(LevelFatal, format, args...) }
func (l *Logger) Dief(format string, args ...interface{}) { l.Fatalf(format, args...); os.Exit(1) }
func (l *Logger) printf(lv Level, format string, args ...interface{}) {
l.mutex.Lock()
defer l.mutex.Unlock()
if l.cfg.Level <= lv {
l.log.Printf("["+lv.String()+"] "+format, args...)
}
}
|