-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.go
265 lines (217 loc) · 7 KB
/
config.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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// Copyright (c) 2022 xybor-x
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package xylog
import (
"io"
"os"
"time"
"github.com/xybor-x/xycond"
"github.com/xybor-x/xyerror"
"github.com/xybor-x/xylock"
"github.com/xybor-x/xylog/encoding"
)
func init() {
rootLogger = newLogger("", nil)
rootLogger.SetLevel(WARNING)
}
// Default levels, these can be replaced with any positive set of values having
// corresponding names. There is a pseudo-level, NOTSET, which is only really
// there as a lower limit for user-defined levels. Handlers and loggers are
// initialized with NOTSET so that they will log all messages, even at
// user-defined levels.
const (
NOTLOG = 1000
CRITICAL = 50
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
)
// startTime is used as the base when calculating the relative time of events.
var startTime = time.Now().UnixMilli()
// globalLock is used to serialize access to shared data structures in this
// module.
var globalLock = &xylock.RWLock{}
// processid is always fixed and used to fill %(process) macro.
var processid = os.Getpid()
// timeLayout is the default time layout used to print asctime when logging.
var timeLayout = time.RFC3339Nano
// rootLogger is the parent Logger of all Loggers in program.
var rootLogger *Logger
// handlerManager is a map to search Handler by name.
var handlerManager = make(map[string]*Handler)
// emitterManager is a list containing all created Emitters in program.
var emitterManager []Emitter
// skipCall is the depth of Logger.log call in program, 3 by default. Increase
// this value if you want to wrap log methods of logger.
var skipCall = 3
// findCaller allows finding caller information including filename, lineno,
// funcname, module.
var findCaller = false
var levelToName = map[int]string{
CRITICAL: "CRITICAL",
ERROR: "ERROR",
WARNING: "WARNING",
INFO: "INFO",
DEBUG: "DEBUG",
NOTSET: "NOTSET",
}
// SetSkipCall sets the new skipCall value which dertermine the depth call of
// Logger.log method.
func SetSkipCall(skip int) {
globalLock.WLockFunc(func() { skipCall = skip })
}
// SetTimeLayout sets the time layout to print asctime. It is time.RFC3339Nano
// by default.
func SetTimeLayout(layout string) {
globalLock.WLockFunc(func() { timeLayout = layout })
}
// SetFindCaller with true to find caller information including filename, line
// number, function name, and module.
func SetFindCaller(b bool) {
globalLock.WLockFunc(func() { findCaller = b })
}
// AddLevel associates a log level with name. It can overwrite other log levels.
// Default log levels:
// NOTSET 0
// DEBUG 10
// INFO 20
// WARN/WARNING 30
// ERROR/FATAL 40
// CRITICAL 50
func AddLevel(level int, levelName string) {
globalLock.WLockFunc(func() { levelToName[level] = levelName })
}
// CheckLevel validates if the given level is associated or not.
func CheckLevel(level int) int {
globalLock.RLock()
defer globalLock.RUnlock()
xycond.AssertIn(level, levelToName)
return level
}
// GetLevelName returns a name associated with the given level.
func GetLevelName(level int) string {
globalLock.RLock()
defer globalLock.RUnlock()
return levelToName[level]
}
// Flush writes unflushed buffered data to outputs.
func Flush() {
globalLock.RLock()
defer globalLock.RUnlock()
for i := range emitterManager {
emitterManager[i].Flush()
}
}
// SimpleConfig supports to quickly create a Logger without configurating
// Emitter and Handler.
type SimpleConfig struct {
// Name is the name of Logger. It can be used later with GetLogger function.
// Default to an empty name (the root logger).
Name string
// Use the specified encoding to format the output. Default to TextEncoding.
Encoding encoding.Encoding
// Specify that Logger will write the output to a file. Do NOT use together
// with Writer.
Filename string
// Specify the mode to open file. Default to APPEND | CREATE | WRONLY.
Filemode int
// Specify the permission when creating the file. Default to 0666.
Fileperm os.FileMode
// The logging level. Default to WARNING.
Level int
// The time layout when format the time string. Default to RFC3339Nano.
TimeLayout string
// Specify that Logger will write the output to a file. Do NOT use together
// with Filename.
Writer io.Writer
macros []macroField
}
// AddMacro adds a macro value to output format.
func (cfg *SimpleConfig) AddMacro(name, value string) *SimpleConfig {
cfg.macros = append(cfg.macros, macroField{key: name, macro: value})
return cfg
}
// Apply creates a Logger based on the configuration.
func (cfg SimpleConfig) Apply() (*Logger, error) {
if cfg.TimeLayout != "" {
SetTimeLayout(cfg.TimeLayout)
}
if cfg.Filename != "" && cfg.Writer != nil {
return nil, xyerror.ParameterError.New("do not set both filename and writer")
}
var filemode = cfg.Filemode
if filemode == 0 {
filemode = os.O_APPEND | os.O_CREATE | os.O_WRONLY
}
var fileperm = cfg.Fileperm
if fileperm == 0 {
fileperm = 0666
}
var writer = cfg.Writer
if writer == nil {
if cfg.Filename == "" {
writer = os.Stderr
} else {
var err error
writer, err = os.OpenFile(cfg.Filename, filemode, fileperm)
if err != nil {
return nil, err
}
}
}
var emitter = NewStreamEmitter(writer)
var enc = cfg.Encoding
if enc == nil {
enc = encoding.NewTextEncoding()
}
var macros = cfg.macros
if macros == nil {
macros = append(macros, macroField{key: "time", macro: "asctime"})
macros = append(macros, macroField{key: "level", macro: "levelname"})
}
var handler = GetHandler("")
handler.AddEmitter(emitter)
handler.SetEncoding(enc)
for i := range macros {
handler.AddMacro(macros[i].key, macros[i].macro)
}
var level = cfg.Level
if level == 0 {
level = WARNING
}
var logger = GetLogger(cfg.Name)
logger.AddHandler(handler)
logger.SetLevel(level)
return logger, nil
}
func makeField(key string, value any) field {
return field{key: key, value: value}
}
type field struct {
key string
value any
}
type macroField struct {
key string
macro string
}