serilog-sinks-file icon indicating copy to clipboard operation
serilog-sinks-file copied to clipboard

Force a File Rollover

Open alistair-ocad opened this issue 1 year ago • 1 comments

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?

alistair-ocad avatar Aug 28 '24 10:08 alistair-ocad

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.

alistair-ocad avatar Aug 30 '24 13:08 alistair-ocad

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

nblumhardt avatar Oct 04 '24 03:10 nblumhardt

Closing as stale; feel free to log any info about whether it worked and/or what you did instead for future travellers...

bartelink avatar Oct 21 '24 08:10 bartelink

Thanks @nblumhardt ! I will have a test sometime in the future when I have a spare hour.

alistair-ocad avatar Oct 29 '24 16:10 alistair-ocad