To rotate the file
Keep track of when the current file was opened, if it is more than a given TimeSpam
(the "10-20 minutes") then close it, create a file filename and open that.
To allow others to read the file
This is all about controlling the file share options, while other methods will do the right defaults, if I need something specific I would rather be explicit. FileShare.Read
has the right semantics:
Allows subsequent opening of the file for reading.
Solution
class FileLogger {
private TimeSpan timeout;
private DateTime openedFile;
private Stream output;
private StreamWriter writer;
public Dispose() {
if (writer != null) {
writer.Dispose();
writer = null;
};
if (output != null) {
output.Dispose();
output = null;
}
}
public void Log(string message) {
if (output == null
|| ((DateTime.UtcNow - openedFile) > timeout) {
Dispose();
string filename = MakeFileName();
output = new FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.Read);
writer = new StreamWriter(output);
openedFile = DateTime.UtcNow;
}
writer.WriteLine(writer);
}
}
But with MakeFileName
implemented and a constructor to set timeout
.