2023-11-28 18:29:30 +08:00
|
|
|
package gologger
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
)
|
|
|
|
|
|
|
|
type FileAppender struct {
|
|
|
|
filePath string
|
2023-12-13 23:05:42 +08:00
|
|
|
lchan chan LogEvent
|
2023-11-28 18:29:30 +08:00
|
|
|
file *os.File
|
2024-09-21 14:25:45 +08:00
|
|
|
stopChan chan struct{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close implements LoggerAppender.
|
|
|
|
func (f *FileAppender) Close() {
|
|
|
|
//send stop signal
|
|
|
|
f.stopChan <- struct{}{}
|
2023-11-28 18:29:30 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (f *FileAppender) GetName() string {
|
|
|
|
return "FileAppender:" + f.filePath
|
|
|
|
}
|
|
|
|
|
2023-12-13 23:05:42 +08:00
|
|
|
func (f *FileAppender) start() {
|
|
|
|
f.lchan = make(chan LogEvent, 10)
|
2024-09-21 14:25:45 +08:00
|
|
|
f.stopChan = make(chan struct{})
|
2023-11-28 18:29:30 +08:00
|
|
|
if f.file == nil || int(f.file.Fd()) == -1 {
|
|
|
|
dirName := filepath.Dir(f.filePath)
|
|
|
|
_, err := os.Stat(dirName)
|
|
|
|
if err != nil && os.IsNotExist(err) {
|
|
|
|
os.MkdirAll(dirName, 0755)
|
|
|
|
}
|
|
|
|
f.file, _ = os.OpenFile(f.filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
|
|
|
}
|
|
|
|
|
2023-12-13 23:05:42 +08:00
|
|
|
go func() {
|
2023-12-13 23:07:32 +08:00
|
|
|
defer f.file.Close()
|
2023-12-13 23:05:42 +08:00
|
|
|
for {
|
2024-09-21 14:25:45 +08:00
|
|
|
select {
|
|
|
|
case <-f.stopChan:
|
|
|
|
return
|
|
|
|
case logEvent := <-f.lchan:
|
|
|
|
logMsg := format(logEvent)
|
|
|
|
f.file.WriteString(logMsg)
|
|
|
|
}
|
|
|
|
|
2023-12-13 23:05:42 +08:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
func (f *FileAppender) Append(logEvent LogEvent) {
|
2023-11-28 18:29:30 +08:00
|
|
|
|
2023-12-13 23:05:42 +08:00
|
|
|
f.lchan <- logEvent
|
2023-11-28 18:29:30 +08:00
|
|
|
}
|
|
|
|
|
2023-12-13 23:05:42 +08:00
|
|
|
func makeFileAppender(appenderConfig LogAppenderConfig) *LoggerAppender {
|
2023-11-28 18:29:30 +08:00
|
|
|
var logfile interface{}
|
|
|
|
var ok bool
|
|
|
|
logfile, ok = appenderConfig.Options["file"]
|
|
|
|
if !ok {
|
|
|
|
logfile = "default.log"
|
|
|
|
}
|
|
|
|
var ret LoggerAppender = &FileAppender{
|
|
|
|
filePath: logfile.(string),
|
|
|
|
}
|
2023-12-13 23:05:42 +08:00
|
|
|
|
|
|
|
ret.(*FileAppender).start()
|
|
|
|
|
|
|
|
return &ret
|
2023-11-28 18:29:30 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
RegistAppender("file", makeFileAppender)
|
|
|
|
}
|