-
Notifications
You must be signed in to change notification settings - Fork 30
/
manager.go
147 lines (108 loc) · 2.35 KB
/
manager.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package golog
import (
"errors"
"io/ioutil"
"os"
"sync"
)
var (
logMap = map[string]*Logger{}
logMapGuard sync.RWMutex
)
func add(l *Logger) {
logMapGuard.Lock()
if _, ok := logMap[l.name]; ok {
panic("duplicate logger name:" + l.name)
}
logMap[l.name] = l
logMapGuard.Unlock()
}
func str2loglevel(level string) Level {
switch level {
case "debug":
return Level_Debug
case "info":
return Level_Info
case "warn":
return Level_Warn
case "error":
return Level_Error
case "fatal":
return Level_Fatal
}
return Level_Debug
}
var ErrLoggerNotFound = errors.New("logger not found")
func VisitLogger(name string, callback func(*Logger) bool) error {
logMapGuard.RLock()
defer logMapGuard.RUnlock()
if name == "*" {
for _, l := range logMap {
if !callback(l) {
break
}
}
} else {
l, ok := logMap[name]
if !ok {
return ErrLoggerNotFound
}
if callback(l) {
return nil
}
}
return nil
}
// 通过字符串设置某一类日志的级别
func SetLevelByString(loggerName string, level string) error {
return VisitLogger(loggerName, func(l *Logger) bool {
l.SetLevelByString(level)
return true
})
}
// 通过字符串设置某一类日志的崩溃级别
func SetPanicLevelByString(loggerName string, level string) error {
return VisitLogger(loggerName, func(l *Logger) bool {
l.SetPanicLevelByString(level)
return true
})
}
func SetColorFile(loggerName string, colorFileName string) error {
data, err := ioutil.ReadFile(colorFileName)
if err != nil {
return err
}
return SetColorDefine(loggerName, string(data))
}
func SetColorDefine(loggerName string, jsonFormat string) error {
cf := NewColorFile()
if err := cf.Load(jsonFormat); err != nil {
return err
}
return VisitLogger(loggerName, func(l *Logger) bool {
l.SetColorFile(cf)
return true
})
}
func EnableColorLogger(loggerName string, enable bool) error {
return VisitLogger(loggerName, func(l *Logger) bool {
l.enableColor = enable
return true
})
}
func SetOutputLogger(loggerName string, filename string) error {
mode := os.O_RDWR | os.O_CREATE | os.O_APPEND
f, err := os.OpenFile(filename, mode, 0666)
if err != nil {
return err
}
return VisitLogger(loggerName, func(l *Logger) bool {
l.fileOutput = f
return true
})
}
func ClearAll() {
logMapGuard.Lock()
logMap = map[string]*Logger{}
logMapGuard.Unlock()
}