Skip to content

Commit

Permalink
Perform file roll only occasionally when file is locked (#3684)
Browse files Browse the repository at this point in the history
  • Loading branch information
nohwnd committed May 30, 2022
1 parent 41bfcfd commit 429af98
Showing 1 changed file with 21 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,9 @@ internal sealed class StreamWriterRollingHelper : IDisposable
/// this listener.
/// </summary>
private TallyKeepingFileStreamWriter _managedWriter;
private bool _lastRollFailed;
private readonly Stopwatch _sinceLastRoll = Stopwatch.StartNew();
private readonly long _failedRollTimeout = TimeSpan.FromMinutes(1).Ticks;

/// <summary>
/// The trace listener for which rolling is being managed.
Expand Down Expand Up @@ -232,6 +235,14 @@ public void RollIfNecessary()
/// <returns>true if update was successful, false if an error occurred.</returns>
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)
{
Expand Down Expand Up @@ -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
{
Expand All @@ -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;
}
}
}
Expand Down

0 comments on commit 429af98

Please sign in to comment.