gologger/file.go

56 lines
1.1 KiB
Go
Raw Normal View History

2023-11-28 18:29:30 +08:00
package gologger
import (
"fmt"
"os"
"path/filepath"
)
type FileAppender struct {
filePath string
file *os.File
}
func (f *FileAppender) GetName() string {
return "FileAppender:" + f.filePath
}
func (f *FileAppender) Append(logEvent LogEvent) {
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)
}
data := []interface{}{
logEvent.Ts.Format("2006-01-02 15:04:05"),
" ",
}
data = append(data, "["+logEvent.Category+"] ")
dmsg := fmt.Sprint(logEvent.Data...)
data = append(data, dmsg)
logMsg := fmt.Sprint(data...)
f.file.WriteString(logMsg + "\n")
}
func makeFileAppender(appenderConfig LogAppenderConfig) LoggerAppender {
var logfile interface{}
var ok bool
logfile, ok = appenderConfig.Options["file"]
if !ok {
logfile = "default.log"
}
var ret LoggerAppender = &FileAppender{
filePath: logfile.(string),
}
return ret
}
func init() {
RegistAppender("file", makeFileAppender)
}