Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Perform file roll only occasionally when file is locked #3684

Merged
merged 1 commit into from
May 30, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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