This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleveledlog.go
110 lines (91 loc) · 2.21 KB
/
leveledlog.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package leveledlog
import (
"fmt"
"io"
"log"
"runtime"
)
const (
NONE = iota
ERROR
WARNING
INFO
DEBUG
)
const (
Ldate = log.Ldate
Ltime = log.Ltime
Lmicroseconds = log.Lmicroseconds
Llongfile = log.Llongfile
Lshortfile = log.Lshortfile
LUTC = log.LUTC
LstdFlags = log.LstdFlags
)
type LeveledLog struct {
logger *log.Logger
loglevel uint32
prefixes [4]string
flags int
}
func New(out io.Writer, loglevel uint32, flag int) *LeveledLog {
var llogger LeveledLog
llogger.logger = log.New(out, "", flag&^Lshortfile&^Llongfile)
llogger.loglevel = loglevel
llogger.prefixes = [4]string{"[ERROR] ", "[WARNING] ", "[INFO] ", "[DEBUG] "}
llogger.flags = flag
return &llogger
}
func DefaultNew(out io.Writer, loglevel uint32) *LeveledLog {
return New(out, loglevel, Ldate|Ltime|Lshortfile)
}
func (llogger *LeveledLog) formatFile(file string, line int) string {
if llogger.flags&(Lshortfile|Llongfile) == 0 {
return ""
}
if llogger.flags&Lshortfile != 0 {
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
file = short
}
return fmt.Sprintf("%s:%d ", file, line)
}
func (llogger *LeveledLog) printf(entrylevel uint32, msg string, v ...interface{}) {
if (entrylevel < ERROR) || (DEBUG < entrylevel) {
return
}
if llogger.loglevel < entrylevel {
return
}
fmsg := fmt.Sprintf(msg, v...)
file := ""
if _, f, l, ok := runtime.Caller(2); ok {
file = llogger.formatFile(f, l)
}
llogger.logger.Printf("%s%s%s\n", file, llogger.prefixes[entrylevel-1], fmsg)
}
func (llogger *LeveledLog) Debug(msg string, v ...interface{}) {
llogger.printf(DEBUG, msg, v...)
}
func (llogger *LeveledLog) Info(msg string, v ...interface{}) {
llogger.printf(INFO, msg, v...)
}
func (llogger *LeveledLog) Warning(msg string, v ...interface{}) {
llogger.printf(WARNING, msg, v...)
}
func (llogger *LeveledLog) Error(msg string, v ...interface{}) {
llogger.printf(ERROR, msg, v...)
}
func (llogger *LeveledLog) SetLevel(level uint32) {
llogger.loglevel = level
}
func (llogger *LeveledLog) SetPrefix(level uint32, prefix string) {
if (level < ERROR) || (DEBUG < level) {
return
}
llogger.prefixes[level-1] = prefix
}