improved access log flushing

This commit is contained in:
yusing 2025-01-04 05:08:23 +08:00
parent 6b669fc540
commit 112859caa5

View file

@ -121,11 +121,15 @@ func (l *AccessLogger) Rotate() error {
} }
func (l *AccessLogger) Flush(force bool) { func (l *AccessLogger) Flush(force bool) {
if l.buf.Len() == 0 {
return
}
if force || l.buf.Len() >= l.flushThreshold { if force || l.buf.Len() >= l.flushThreshold {
l.bufMu.Lock() l.bufMu.Lock()
l.write(l.buf.Bytes()) l.write(l.buf.Bytes())
l.buf.Reset() l.buf.Reset()
l.bufMu.Unlock() l.bufMu.Unlock()
logger.Debug().Msg("access log flushed to " + l.io.Name())
} }
} }
@ -142,14 +146,19 @@ func (l *AccessLogger) start() {
l.task.Finish(nil) l.task.Finish(nil)
}() }()
// threshold flush with periodic check // periodic flush + threshold flush
flushTicker := time.NewTicker(time.Second) periodic := time.NewTicker(5 * time.Second)
threshold := time.NewTicker(time.Second)
defer periodic.Stop()
defer threshold.Stop()
for { for {
select { select {
case <-l.task.Context().Done(): case <-l.task.Context().Done():
return return
case <-flushTicker.C: case <-periodic.C:
l.Flush(true)
case <-threshold.C:
l.Flush(false) l.Flush(false)
} }
} }