Serilog is one of the most popular structured logging libraries for .NET, offering excellent performance and flexibility. While Serilog comes with many built-in sinks for common destinations like files, databases, and cloud services, we created a custom sink to guarantee compatibility with an existing legacy logging solution. However as we noticed some performance issues, we decided to rewrite the implementation to use a batched sink.
In this post, we'll explore how to build your own batched sink in Serilog, which can significantly improve performance when dealing with high-volume logging scenarios. At least that is what we are aiming for…
Understanding Serilog's batched sink architecture
Serilog has built-in batching support and handles most of the complexity of batching log events for you. Internally will handle things like:
- Collecting log events in an internal queue
- Periodically flushing batches based on time intervals or batch size limits
- Handling backpressure when the queue becomes full
- Providing thread-safe operations
The only thing that we need to do is implement the IBatchedLogEventSink
interface.
Step 1 - Create the sink class
We start by implementing the IBatchedLogEventSink
interface.
Step 2: Create an extension method
To make your sink easy to use, create an extension method following Serilog conventions:
As we allow to pass a BatchingOptions
instance, you are in full control on how the Serilog Batched sink should behave.
Happy coding!