access logger support sharing the same file, tests added for concurrent logging

This commit is contained in:
yusing
2025-01-03 14:10:09 +08:00
parent 753e193d62
commit 6e30d39b78
5 changed files with 211 additions and 91 deletions

View File

@@ -13,10 +13,26 @@ type File struct {
sync.Mutex
}
var (
openedFiles = make(map[string]AccessLogIO)
openedFilesMu sync.Mutex
)
func NewFileAccessLogger(parent task.Parent, cfg *Config) (*AccessLogger, error) {
f, err := os.OpenFile(cfg.Path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return nil, fmt.Errorf("access log open error: %w", err)
openedFilesMu.Lock()
var io AccessLogIO
if opened, ok := openedFiles[cfg.Path]; ok {
io = opened
} else {
f, err := os.OpenFile(cfg.Path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return nil, fmt.Errorf("access log open error: %w", err)
}
io = &File{File: f}
openedFiles[cfg.Path] = io
}
return NewAccessLogger(parent, &File{File: f}, cfg), nil
openedFilesMu.Unlock()
return NewAccessLogger(parent, io, cfg), nil
}