-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_logger.go
111 lines (87 loc) · 1.89 KB
/
file_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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package glogger
import (
"github.com/sirupsen/logrus"
"os"
"sync"
)
// keep files open and write on log file in an interval if it is production level
// delete, openFiles if it is closed.
// close open files when shutting down the file
var openFiles sync.Map
type FileLogger struct {
level LogLevel
name string
logger *logrus.Logger
}
// NewFileLogger creates a new file logger
func NewFileLogger(name string) *FileLogger {
var file *os.File
existedFile, ok := openFiles.Load(name)
if !ok {
newFile, err := os.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
logrus.Error("Failed to open log file:", err)
}
file = newFile
openFiles.Store(name, newFile)
} else {
file = existedFile.(*os.File)
}
logger := logrus.New()
logger.SetOutput(file)
return &FileLogger{name: name, logger: logger}
}
func (l *FileLogger) Error(args ...any) {
//if !std.allowed() {
// return
//}
if !isAllowed(ErrorLevel) {
return
}
l.logger.Error(args...)
}
func (l *FileLogger) Errorf(format string, args ...any) {
if !isAllowed(ErrorLevel) {
return
}
l.logger.Errorf(format, args...)
}
func (l *FileLogger) Warn(args ...any) {
if !isAllowed(WarnLevel) {
return
}
}
func (l *FileLogger) Warnf(format string, args ...any) {
if !isAllowed(WarnLevel) {
return
}
}
func (l *FileLogger) Info(args ...any) {
if !isAllowed(InfoLevel) {
return
}
}
func (l *FileLogger) Infof(format string, args ...any) {
if !isAllowed(InfoLevel) {
return
}
}
func (l *FileLogger) Debug(args ...any) {
l.logger.Debug(args...)
}
func (l *FileLogger) Debugf(format string, args ...any) {
l.logger.Debugf(format, args...)
}
func (l *FileLogger) WithLevel(level LogLevel) *FileLogger {
l.level = level
return l
}
func Shutdown() error {
openFiles.Range(func(key, value any) bool {
file := value.(*os.File)
file.Close()
openFiles.Delete(key)
return true
})
return nil
}