From ccda4e73f35799cc0d948b512b61b649dbbd360c 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 | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/klog.go b/klog.go index 026be9e3..fb775ca8 100644 --- a/klog.go +++ b/klog.go @@ -1012,6 +1012,7 @@ func (l *loggingT) exit(err error) { return } l.flushAll() + l.syncAll() OsExit(2) } @@ -1225,9 +1226,11 @@ func (l *loggingT) lockAndFlushAll() { l.mu.Lock() l.flushAll() l.mu.Unlock() + // Some environments are slow when syncing and holding the lock might cause contention. + l.syncAll() } -// flushAll flushes all the logs and attempts to "sync" their data to disk. +// flushAll flushes all the logs // l.mu is held. func (l *loggingT) flushAll() { // Flush from fatal down, in case there's trouble flushing. @@ -1235,7 +1238,6 @@ func (l *loggingT) flushAll() { file := l.file[s] if file != nil { _ = file.Flush() // ignore error - _ = file.Sync() // ignore error } } if logging.loggerOptions.flush != nil { @@ -1243,6 +1245,17 @@ func (l *loggingT) flushAll() { } } +// syncAll attempts to "sync" their data to disk. +func (l *loggingT) syncAll() { + // 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.Sync() // ignore error + } + } +} + // CopyStandardLogTo arranges for messages written to the Go "log" package's // default logs to also appear in the Google logs for the named and lower // severities. Subsequent changes to the standard log's default output location