From 90280d9ab3808096d5307614496d01aefcd63c26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Thu, 26 May 2022 14:55:41 +0200 Subject: [PATCH] Perform file roll only occasionally when file is locked --- .../Tracing/RollingFileTraceListener.cs | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/common/Tracing/RollingFileTraceListener.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/common/Tracing/RollingFileTraceListener.cs index a4dae6ddb5..7324c82cee 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/common/Tracing/RollingFileTraceListener.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/common/Tracing/RollingFileTraceListener.cs @@ -128,6 +128,9 @@ internal sealed class StreamWriterRollingHelper : IDisposable /// this listener. /// private TallyKeepingFileStreamWriter _managedWriter; + private bool _lastRollFailed; + private readonly Stopwatch _sinceLastRoll = Stopwatch.StartNew(); + private readonly long _failedRollTimeout = TimeSpan.FromMinutes(1).Ticks; /// /// The trace listener for which rolling is being managed. @@ -232,6 +235,14 @@ public void RollIfNecessary() /// true if update was successful, false if an error occurred. public bool UpdateRollingInformationIfNecessary() { + // if we fail to move the file, don't retry to move it for a long time + // it is most likely locked, and we end up trying to move it twice + // on each message write. + if (_lastRollFailed && _sinceLastRoll.ElapsedTicks < _failedRollTimeout) + { + return false; + } + // replace writer with the tally keeping version if necessary for size rolling if (_managedWriter == null) { @@ -260,7 +271,7 @@ public void Dispose() GC.SuppressFinalize(this); } - private static void SafeMove(string actualFileName, string archiveFileName, DateTime currentDateTime) + private void SafeMove(string actualFileName, string archiveFileName, DateTime currentDateTime) { try { @@ -272,18 +283,27 @@ private static void SafeMove(string actualFileName, string archiveFileName, Date // take care of tunneling issues http://support.microsoft.com/kb/172190 File.SetCreationTime(actualFileName, currentDateTime); File.Move(actualFileName, archiveFileName); + + _lastRollFailed = false; + _sinceLastRoll.Restart(); } catch (IOException) { + _lastRollFailed = true; + // catch errors and attempt move to a new file with a GUID archiveFileName += Guid.NewGuid().ToString(); try { File.Move(actualFileName, archiveFileName); + + _lastRollFailed = false; + _sinceLastRoll.Restart(); } catch (IOException) { + _lastRollFailed = true; } } }