serilog-sinks-file
serilog-sinks-file copied to clipboard
Force a File Rollover
I would like a mechanism to close the existing file-sink which will in turn start a new one.
Scenario: I'm build apps with .Net Maui and use Serilog, also using dependency injection to instantiate the Serilog service. I'd like to build a UI which allows the user to send me the log file(s) while running the app. Because the logs are often in obscure places dependant on the device it is unrealistic for the user to know how to find them. The plan is to present the list of log files (I use size + day rollovers) to the user (which includes the active file-sink) and the user can select 1-n and clink on Send. I would then want to rollover the active file-sink to a new file and send the existing file(s) to a server etc.
Describe the solution you'd like Maybe some sort of hook function to force the rollover?
Describe alternatives you've considered This is similar to the delete scenarios presented in other issues, in that a file is re-created if it is missing. I could somehow create a hacked solution using this scenario but it doesn't feel quite right.
Please close this issue if it's already implemented in some way, and please let me know how?
As a hack-workaround for now i do the following:
Don't use DI, I have a service class that creates and deletes the LoggerConfiguration.
If I need to upload the current log I Dispose the Logger (forces the close).
Then I create a new empty file-stream of the same filename but incremented with the 00# +1 etc.
Make sure the new file stream is closed.
Send the original file to a server etc.
Restart the logger, this will use the newly created (empty) file. Thus there is no duplicated log data.
It's a bit annoying not to use the ILogger in the dependany injection directly, but I can use my service (with DI) instead which has a property of the current Logger object.
Hi @alistair-ocad,
This can be achieved by adding the Serilog.Sinks.Map package and using this trick:
// somewhere
static volatile int _version;
Log.Logger = new LoggerConfiguration()
.WriteTo.Map(
_ => _version,
(wt, v) => wt.File($"log-{v}-.txt", ...),
sinkMapCountLimit: 1)
.CreateLogger();
To cause a roll-over, increment _version.
Hope this helps, Nick
Closing as stale; feel free to log any info about whether it worked and/or what you did instead for future travellers...
Thanks @nblumhardt ! I will have a test sometime in the future when I have a spare hour.