In my post yesterday, I showed how to configure rolling and retention so a runaway log file no longer fills your disk. That solves the problem, but it leaves a question open: what if you want to do something with those files before they disappear? Note: This post is a follow-up on Cleaning up old log files with Serilog . Maybe you want to compress the files to save space. Maybe compliance requires you to archive them first. Serilog.Sinks.File has an extension point for this: FileLifecycleHooks . What are FileLifecycleHooks? A lifecycle hook lets you run your own code at specific moments in the life of a log file. You inherit from the abstract class FileLifecycleHooks and override one or both of these methods: OnFileOpened : called when the sink opens a new log file. You receive the underlying stream and can return your own stream that wraps it. OnFileDeleting : called just before a file is deleted by the retention policy. Both have a default implementation that do...
We got an alert from our ops team: the disk of one of our servers was filling up. The culprit was a log file that grew so fast it ate all the available space. The dev team didn't configured any cleanup, so the file just kept growing. The application was already using Serilog . Let's have a look what options we have available to limit the amount of log data. The default config The simplest way to write a log file with Serilog looks like this: Log.Logger = new LoggerConfiguration() .WriteTo.File("logs/log.txt") .CreateLogger(); This works, but it writes everything to one single file. By default, no rolling happens and nothing gets deleted. Remark: This isn’t entirely true. The file sink has a default fileSizeLimitBytes of 1 GB. When the file reaches that limit, Serilog silently stops writing log events. So you don’t fill your disk, but you lose your logs. That’s not much better. Rolling files The first step is to start a new file at regular int...