This repository has been archived by the owner on Sep 12, 2023. It is now read-only.
forked from amenzhinsky/iothub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
88 lines (74 loc) · 1.75 KB
/
logger.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package logger
import (
"fmt"
"log"
)
// Logger is common logging interface.
type Logger interface {
Errorf(format string, v ...interface{})
Warnf(format string, v ...interface{})
Infof(format string, v ...interface{})
Debugf(format string, v ...interface{})
}
// Level is logging severity.
type Level uint8
const (
LevelOff Level = iota
LevelError
LevelWarn
LevelInfo
LevelDebug
)
// String returns log level string representation.
func (lvl Level) String() string {
switch lvl {
case LevelOff:
return "OFF"
case LevelError:
return "ERROR"
case LevelWarn:
return "WARN"
case LevelInfo:
return "INFO"
case LevelDebug:
return "DEBUG"
default:
return fmt.Sprintf("UNKNOWN(%d)", lvl)
}
}
// OutputFunc prints logs.
type OutputFunc func(lvl Level, s string)
// New creates a new leveled logger instance with the given parameters.
//
// If out is nil it uses the standard logger for output.
func New(lvl Level, out OutputFunc) *LevelLogger {
if out == nil {
out = logStd
}
return &LevelLogger{lvl: lvl, out: out}
}
func logStd(lvl Level, s string) {
_ = log.Output(4, fmt.Sprint(lvl.String(), " ", s))
}
// LevelLogger is a logger that supports log levels.
type LevelLogger struct {
lvl Level
out OutputFunc
}
func (l *LevelLogger) Errorf(format string, v ...interface{}) {
l.logf(LevelError, format, v...)
}
func (l *LevelLogger) Infof(format string, v ...interface{}) {
l.logf(LevelInfo, format, v...)
}
func (l *LevelLogger) Warnf(format string, v ...interface{}) {
l.logf(LevelWarn, format, v...)
}
func (l *LevelLogger) Debugf(format string, v ...interface{}) {
l.logf(LevelDebug, format, v...)
}
func (l *LevelLogger) logf(lvl Level, format string, v ...interface{}) {
if lvl <= l.lvl {
l.out(lvl, fmt.Sprintf(format, v...))
}
}