Reputation: 3899
EDIT: The below accepted answer works partially. It does defer file creation, but it does not respect a minimum LogEventLevel
(since the deferred line is called whenever logging occurs, even if it ends up not writing to the file). It does, however, accomplish my overarching goal of "no blank file creation" (and I will just log errors in my application), so I'm keeping it as the accepted answer.
My final code looks like this:
new LoggerConfiguration().WriteTo.Map("", "", (_, writeTo) => writeTo.File("SampleName.log")).CreateLogger();
I have a simple console application in which I'm using Serilog and a File sink:
new LoggerConfiguration().WriteTo.File("SampleName.log", LogEventLevel.Error).CreateLogger();
Ideally, I would only want it to create a log file on disk when there is something to log (errors in my scenario). However, if the application runs and completes without errors, Serilog will still create an empty file. Is there a way to instruct Serilog to only create a file when it has something to log?
Upvotes: 3
Views: 1649
Reputation: 27868
This is not possible as of this writing. The file is created on disk as soon as the FileSink
instance is created and there's no configuration option to change that behavior.
You could create a sink that wraps the FileSink
and lazily create the FileSink
instance whenever the first log event is emitted.
Or, you could delete the empty file at the end, just before your app ends (but after you call Log.CloseAndFlush
).
Upvotes: 3