Rolling log file writer: avoid truncating file when rotating #144
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There are several conditions under which the rotating log file writer can actually truncate the file it is rotating.
Principally, this is caused by a lack of locking when writing to the log file. In
rollingFileWriter.Write()
, we test for whether the current file needs to be rotated, and if so then perform the rotation. This needs locking to ensure that we do not have two (or more) goroutines making the decision to rotate, then rotating. If this occurs then the second rotation of an empty or virtually-empty file will truncate the original file's contents. This commit resolves the problem by adding mutex locking toWrite()
.There is also a more convoluted path through the time-based file writer code which (previously) checked the modification time of the file on disk, meaning that a mutex in the
Write()
routine alone is not sufficient. This commit also changes the time-based tests to cache the time and filename, removing the need for a call toos.Stat()
and removing the possibility of making an inconsistent decision to roll more than once.Fixes #143. Supersedes #135.