-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfiplog.go
332 lines (292 loc) · 6.92 KB
/
fiplog.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/*
Pacakge fiplog provides log wrapper
*/
package fiplog
import (
"fmt"
"github.com/fipress/fml"
"io"
"log"
"os"
"regexp"
"runtime"
"strings"
"sync"
"time"
)
type Level int
const (
LevelDebug Level = iota
LevelInfo
LevelWarning
LevelError
)
var prefix = [4]string{"DEBUG", "INFO", "WARNING", "ERROR"}
const (
defaultBufferSize = 4096
defaultDateFormat = `%df{2006-01-02 15:04:05}`
//defaultPattern = `%date [%level] %file - %msg`
defaultPattern = `%df{2006-01-02 15:04:05} [%level] %file - %msg`
dateF = "%date"
fileF = "%file"
levelF = "%level"
msgF = "%msg"
)
var dateFormatR = regexp.MustCompile(`%df\{(.*)\}`)
type Config struct {
Level Level
//levelTo Level
Filename string
BufSize int
//size todo: rolling
Pattern string //todo: pattern
}
type FIPLogger struct {
//config *Config
mutex sync.Mutex
level Level
//levelTo Level
buffer []byte
bufSize int
//format string
writer io.WriteCloser
pattern string
ch chan bool
flushMu sync.Mutex
/*debugLogger *log.Logger
infoLogger *log.Logger
warnLogger *log.Logger
errorLogger *log.Logger*/
}
var (
//discard = log.New(ioutil.Discard,"",0)
//discard io.WriteCloser = fakeio(0)
logger *FIPLogger
)
func GetLogger() *FIPLogger {
if logger == nil {
Init()
}
return logger
}
func Init() {
if logger == nil {
//config := &Config{LevelWarning, "stdout",4096,"%df{2006-01-02 15:04} [%level] %file - %msg"} //todo: read config file
//wd := os.Getwd()
fml, err := fml.Load("fiplog.conf")
if err != nil {
fmt.Println("fiplog.conf not found, use default config.")
config := &Config{LevelInfo, "", defaultBufferSize, defaultPattern}
InitWithConfig(config)
} else {
InitWithFml(fml)
}
}
}
func InitWithFml(fml *fml.FML) {
config := new(Config)
config.Filename = fml.GetString("file")
config.Level = getLevel(fml.GetString("level"))
config.BufSize = fml.GetIntOrDefault("bufSize", defaultBufferSize)
config.Pattern = fml.GetStringOrDefault("pattern", defaultPattern)
logger = InitWithConfig(config)
}
func InitWithConfig(config *Config) *FIPLogger {
if logger == nil {
logger = new(FIPLogger)
logger.level = config.Level
if config.BufSize <= 0 {
logger.bufSize = defaultBufferSize
} else {
logger.bufSize = config.BufSize
}
if logger.level != LevelDebug {
logger.buffer = make([]byte, 0, logger.bufSize)
}
if config.Pattern == "" {
logger.pattern = defaultPattern
} else if strings.Contains(config.Pattern, dateF) {
logger.pattern = strings.Replace(config.Pattern, dateF, defaultDateFormat, 1)
} else {
logger.pattern = config.Pattern
}
if len(config.Filename) == 0 {
logger.writer = os.Stdout
} else {
logger.writer = openFile(config.Filename)
}
/*out := strings.ToLower(config.out)
switch out {
case "stdout":
logger.writer = os.Stdout
case "stderr":
logger.writer = os.Stderr
default:
logger.writer = openFile(out)
}
flag := log.Ldate|log.Ltime | log.Lshortfile
switch config.level {
case Debug:
logger.debugLogger = log.New(writer, "DEBUG", flag)
fallthrough
case Info:
logger.infoLogger = log.New(writer, "INFO", flag)
fallthrough
case Warn:
logger.warnLogger = log.New(writer, "WARN", flag)
fallthrough
case Error:
logger.errorLogger = log.New(writer, "ERROR", flag)
}*/
}
return logger
}
func (l *FIPLogger) Close() {
l.flush(true)
}
func getLevel(s string) Level {
switch strings.ToUpper(s) {
case "DEBUG":
return LevelDebug
case "INFO":
return LevelInfo
case "WARNING":
return LevelWarning
case "ERROR":
return LevelError
}
return LevelInfo
}
func (l *FIPLogger) format(level Level, msg string) (formatted string) {
formatted = l.pattern
if dateFormatR.MatchString(formatted) {
now := time.Now()
dt := now.Format(dateFormatR.FindStringSubmatch(formatted)[1])
formatted = dateFormatR.ReplaceAllString(formatted, dt)
}
if strings.Contains(formatted, fileF) {
counter, file, line, ok := runtime.Caller(3)
if !ok {
file = "???"
line = 0
}
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
fs := fmt.Sprintf("<%d>%v:%v", counter, short, line)
formatted = strings.Replace(formatted, fileF, fs, 1)
}
if strings.Contains(formatted, levelF) {
formatted = strings.Replace(formatted, levelF, prefix[level], 1)
}
formatted = strings.Replace(formatted, msgF, msg, 1)
return
}
func (l *FIPLogger) log(level Level, msg string) {
if level < l.level {
return
}
formatted := l.format(level, msg)
if l.writer == os.Stdout || l.level == LevelDebug {
l.writer.Write([]byte(formatted))
} else {
l.mutex.Lock()
if len(l.buffer)+len(formatted) > l.bufSize || level == LevelError {
go l.flush(false)
l.buffer = make([]byte, 0, logger.bufSize)
}
l.buffer = append(l.buffer, formatted...)
len := len(formatted)
if len > 0 && formatted[len-1] != '\n' {
l.buffer = append(l.buffer, '\n')
}
l.mutex.Unlock()
}
/*now := time.Now()
var file string
var line int
l.mu.Lock()
defer l.mu.Unlock()
if l.flag&(Lshortfile|Llongfile) != 0 {
// release lock while getting caller info - it's expensive.
l.mu.Unlock()
var ok bool
_, file, line, ok = runtime.Caller(2)
if !ok {
file = "???"
line = 0
}
l.mu.Lock()
}
l.buf = l.buf[:0]
l.formatHeader(&l.buf, now, file, line)
l.buf = append(l.buf, s...)
if len(s) > 0 && s[len(s)-1] != '\n' {
l.buf = append(l.buf, '\n')
}
_, err := l.out.Write(l.buf)*/
return
}
func (l *FIPLogger) Debug(v ...interface{}) {
msg := fmt.Sprintln(v...)
l.log(LevelDebug, msg)
}
func (l *FIPLogger) Debugf(format string, v ...interface{}) {
msg := fmt.Sprintf(format, v...)
l.log(LevelDebug, msg)
}
func (l *FIPLogger) Info(v ...interface{}) {
msg := fmt.Sprintln(v...)
l.log(LevelInfo, msg)
}
func (l *FIPLogger) Infof(format string, v ...interface{}) {
msg := fmt.Sprintf(format, v...)
l.log(LevelInfo, msg)
}
func (l *FIPLogger) Warning(v ...interface{}) {
msg := fmt.Sprintln(v...)
l.log(LevelWarning, msg)
}
func (l *FIPLogger) Warningf(format string, v ...interface{}) {
msg := fmt.Sprintf(format, v...)
l.log(LevelWarning, msg)
}
func (l *FIPLogger) Error(v ...interface{}) {
msg := fmt.Sprintln(v...)
l.log(LevelError, msg)
}
func (l *FIPLogger) Errorf(format string, v ...interface{}) {
msg := fmt.Sprintf(format, v...)
l.log(LevelError, msg)
}
func (l *FIPLogger) Flush() {
l.flush(false)
}
func (l *FIPLogger) flush(close bool) {
if logger.bufSize == 0 {
return
}
l.flushMu.Lock()
//log.Println("flush buffer lenght:",len(buffer))
_, err := l.writer.Write(l.buffer)
if err != nil {
fmt.Println("Flush log error:", err)
}
if close {
l.writer.Close()
}
l.flushMu.Unlock()
}
func openFile(name string) io.WriteCloser {
file, err := os.OpenFile(name, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.FileMode(0644))
if err != nil {
log.Println("Open log file failed, filename:", name, ",err:", err)
return os.Stdout
} else {
return file
}
}