From a3c171834978af8568d46a15e28133f75b938d00 Mon Sep 17 00:00:00 2001 From: chenpu <1102509144@163.com> Date: Mon, 8 Apr 2024 21:26:11 +0800 Subject: [PATCH] Do not acquire lock for file.Sync() fsync call --- klog.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/klog.go b/klog.go index 026be9e3..dd93d529 100644 --- a/klog.go +++ b/klog.go @@ -1230,17 +1230,28 @@ func (l *loggingT) lockAndFlushAll() { // flushAll flushes all the logs and attempts to "sync" their data to disk. // l.mu is held. func (l *loggingT) flushAll() { + // Remember where we flushed, so we can call sync without holding + // the lock. + var files []flushSyncWriter + // Flush from fatal down, in case there's trouble flushing. for s := severity.FatalLog; s >= severity.InfoLog; s-- { file := l.file[s] if file != nil { _ = file.Flush() // ignore error - _ = file.Sync() // ignore error + files = append(files, file) } } if logging.loggerOptions.flush != nil { logging.loggerOptions.flush() } + + l.mu.Unlock() + // Some environments are slow when syncing and holding the lock might cause contention. + for _, file := range files { + _ = file.Sync() // ignore error + } + l.mu.Lock() } // CopyStandardLogTo arranges for messages written to the Go "log" package's