serilog configuration example

April 11, 2026

Sabrina

Serilog File Sink Example: A 2026 Guide

🎯 Quick AnswerA Serilog file sink example involves configuring Serilog to write log events to files, often with options for rolling, formatting (like JSON or plain text), and retention policies. This is critical for debugging and monitoring .NET applications in real-time.

Serilog File Sink Example: A 2026 Developer’s Handbook

Mastering Serilog file sink examples is essential for any .NET developer in 2026 looking to implement robust application logging. This guide dives into practical, up-to-date configurations for writing logs to files, ensuring you can effectively capture, manage, and analyze your application’s runtime data.

(Source: github.com)

What is a Serilog File Sink and Why Use It in 2026?

A Serilog file sink is a component within the Serilog logging framework that directs log events to a file on disk. In 2026, with the increasing complexity of applications and the rise of distributed systems, effective file logging remains a cornerstone of application observability. It provides a persistent, accessible record of events, crucial for troubleshooting errors, auditing user actions, and understanding application behavior over time.

The necessity for detailed file logging has only intensified. With AI-driven monitoring tools becoming more prevalent, well-structured log files are prime candidates for automated analysis and anomaly detection. A well-configured file sink ensures that the data fed into these AI systems is accurate and actionable.

Table of Contents

What is a Basic Serilog File Sink Setup?

A basic Serilog file sink setup involves initializing Serilog with a `WriteTo.File()` call. This is the most straightforward way to start logging to a file. You specify the path where the log file should be created.

For instance, in your application’s startup code (e.g., `Program.cs` in .NET 6+ or `Startup.cs` in older versions), you would configure Serilog like this:

Expert Tip: Always ensure the directory specified for your log files exists and that your application has the necessary write permissions. Failure to do so is a common pitfall that prevents logging from working.

Here’s a minimal code example:


using Serilog;

public class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Information()
            .WriteTo.File("logs/myapp-.txt", rollingInterval: RollingInterval.Day)
            .CreateLogger();

        try
        {
            Log.Information("Starting application...");
            // Your application logic here
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Application terminated unexpectedly");
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }
}

In this example, `logs/myapp-.txt` specifies the log file path. The hyphen followed by an empty space implies that Serilog will append a date or other interval marker automatically. The `rollingInterval: RollingInterval.Day` setting ensures that a new log file is created each day, preventing single files from becoming excessively large.

How to Configure Rolling File Sink for Log Rotation?

Log rotation is crucial for managing disk space and keeping log files manageable. Serilog’s `RollingFile` sink provides several options for controlling when and how log files are rolled over.

The `rollingInterval` parameter is key. Common values include `RollingInterval.Minute`, `RollingInterval.Hour`, `RollingInterval.Day`, `RollingInterval.Month`, and `RollingInterval.Year`. This determines how frequently a new log file is generated.

Additionally, you can control the maximum number of retained log files using `retainedFileCountLimit`. This prevents your disk from filling up with old logs.

Consider this configuration:


Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.File(
        "logs/app-.log", 
        rollingInterval: RollingInterval.Hour, 
        retainedFileCountLimit: 30,
        outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {Level:u3}] {Message:lj}{NewLine}{Exception}"
    )
    .CreateLogger();

This setup logs to `logs/app-.log`, creates a new file every hour, and keeps the last 30 log files. The `outputTemplate` defines the format of each log entry, including timestamp, level, message, and any exceptions. This level of control is vital for maintaining efficient logging infrastructure.

The importance of log rotation cannot be overstated, especially in high-throughput applications. Failing to rotate logs can lead to performance degradation and disk exhaustion. – Source: DotNetCoreTips.dev (April 2026)

Can I Use a Serilog JSON File Sink Example?

Absolutely. Structured logging, particularly in JSON format, is highly recommended in 2026 for easier parsing by both humans and machines (like AI analysis tools). Serilog makes this simple with its `WriteTo.File()` sink by specifying a JSON output template.

To log in JSON format, you typically use a template that serializes the log event properties into a JSON structure. Serilog provides built-in support for this. A common approach is to use the `LogEvent.Properties` directly.

Here’s a Serilog JSON file sink example:


Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Information()
    .WriteTo.File(new Serilog.Formatting.Json.JsonFormatter(),
        "logs/app-.json", 
        rollingInterval: RollingInterval.Month,
        retainedFileCountLimit: 12)
    .CreateLogger();

In this example, `new Serilog.Formatting.Json.JsonFormatter()` is passed to the `WriteTo.File` method. This tells Serilog to format each log entry as a JSON object. Each line in the log file will be a self-contained JSON document, which is incredibly useful for feeding into log aggregation systems like Elasticsearch, Splunk, or even for direct analysis by AI platforms.

The resulting JSON log entries are easily queryable and machine-readable, significantly enhancing your ability to perform deep dives into application behavior.

What Are Advanced Serilog File Sink Options?

Beyond basic rotation and JSON formatting, Serilog offers advanced options to fine-tune your file logging. These include controlling file size limits, asynchronous writing, and custom formatting.

File Size Limits: You can set a maximum file size before rolling over using `fileSizeLimitBytes`.

Asynchronous Logging: For performance-critical applications, `WriteTo.Async()` can be wrapped around the file sink to prevent logging operations from blocking your application’s main threads.

Custom Formatting: While JSON is popular, you might need custom text formats. You can achieve this by creating your own `Serilog.Formatting.ITextFormatter` implementation.

Here’s an example demonstrating asynchronous writing and a file size limit:


Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .WriteTo.Async(wt => wt.File(
        "logs/perf-.log", 
        rollingInterval: RollingInterval.Day,
        fileSizeLimitBytes: 10  1024  1024, // 10 MB
        outputTemplate: "{Timestamp:o} [{Level}] {Message}{NewLine}{Exception}"
    ))
    .CreateLogger();

This configuration logs verbose messages to `logs/perf-.log`, rolls over daily, limits files to 10MB, and uses asynchronous writing. The `outputTemplate` uses the ISO 8601 format (`o`) for timestamps, which is excellent for consistency.

Controlling Log File Access

It’s also possible to control file access permissions. While not a direct Serilog sink option, this is handled at the operating system level. Ensure your application’s service account has the appropriate read/write permissions for the log directory.

XML File Sink

For specific use cases requiring XML, Serilog doesn’t have a built-in XML formatter as commonly as JSON. However, you can achieve this by creating a custom formatter or by using a third-party package if available. The principle remains the same: define how each log event should be serialized into the desired format.

Feature Description Use Case
rollingInterval Determines how often a new log file is created (e.g., hourly, daily). Managing log file size and organization.
retainedFileCountLimit Sets the maximum number of log files to keep. Preventing disk space exhaustion.
fileSizeLimitBytes Sets the maximum size for a single log file before rolling. Ensuring individual files remain manageable.
outputTemplate Defines the structure and content of each log entry. Customizing log message format for readability or machine parsing.
WriteTo.Async() Enables asynchronous logging to improve application performance. High-throughput or performance-sensitive applications.

What Are the Best Practices for File Logging with Serilog?

Effective file logging goes beyond just setting up a sink. In 2026, best practices are heavily influenced by the need for machine readability and AI integration.

Important: Avoid logging sensitive information like passwords or credit card numbers directly into log files. If necessary, use Serilog’s filtering capabilities or implement data masking techniques before the log event is written.

Here are key best practices:

  1. Use Structured Logging (JSON): As demonstrated, JSON format is ideal for machine parsing and AI analysis. It ensures consistency and makes querying much simpler.

    Serilog File Sink Documentation is an excellent resource for further details.

  2. Implement Sensible Rotation and Retention: Configure `rollingInterval` and `retainedFileCountLimit` based on your application’s expected log volume and your disk space constraints. Don’t keep logs longer than necessary for compliance or debugging.
  3. Define a Clear `outputTemplate`:** Ensure your template includes essential information like timestamps (with timezone), log level, the message itself, and crucially, any exception details. Use consistent formatting.
  4. Filter Appropriately: Use `MinimumLevel` and `Filter` methods to ensure you’re only logging what’s necessary. Logging too much can obscure critical information and waste resources. For example, `MinimumLevel.Error()` in production for general logs, while keeping `Debug` or `Verbose` for specific troubleshooting scenarios.
  5. Consider Asynchronous Logging: For applications where every millisecond counts, wrap your file sink in `WriteTo.Async()` to decouple logging from your application’s critical paths.
  6. Monitor Log File Growth: Regularly check the disk space used by your log files. Implement alerts if they exceed predefined thresholds.
  7. Secure Log Files: Restrict file system access to log directories to authorized personnel and services only.

By adhering to these practices, you ensure your Serilog file sink examples are not just functional but also contribute to a maintainable, observable, and secure application environment in 2026 and beyond.

Frequently Asked Questions

What is the default file name format for Serilog?

The default file name format for Serilog’s file sink, when using `rollingInterval`, typically includes a template where Serilog inserts the appropriate date/time or sequence number. For example, `myapp-.txt` might become `myapp-20260411.txt` or `myapp-001.txt` depending on the rolling interval and configuration.

How do I configure Serilog to log to multiple files?

To log to multiple files simultaneously, you simply chain multiple `WriteTo.File()` calls in your `LoggerConfiguration`. Each call can specify a different path, format, or rolling interval, allowing for specialized log files (e.g., one for errors, one for general info).

Can Serilog delete old log files automatically?

Yes, Serilog’s file sink supports automatic deletion of old log files through the `retainedFileCountLimit` parameter. This parameter specifies the maximum number of log files to keep, ensuring that older files are automatically purged.

What is the difference between `rollingInterval` and `fileSizeLimitBytes`?

`rollingInterval` dictates when a new log file is created based on time (e.g., every hour). `fileSizeLimitBytes` dictates when a new log file is created based on the current file reaching a specific size limit, regardless of the time.

How can I include custom properties in my Serilog file logs?

You can enrich log events with custom properties using Serilog’s `enrichers`. For example, you can add a `MachineName` enricher or create your own custom enricher to add specific context to every log message written to the file sink.

Conclusion: Mastering Your Log Files with Serilog

Implementing effective Serilog file sink examples is a fundamental skill for modern .NET development. By leveraging structured logging, sensible rotation policies, and advanced configurations, you create a powerful tool for application diagnostics and monitoring. The examples and best practices discussed here provide a solid foundation for managing your application’s logs efficiently in 2026.

Start implementing these configurations today to gain deeper insights into your application’s behavior and ensure a more stable, observable system.

Editorial TeamOur team creates thoroughly researched, helpful content. Every article is fact-checked and updated regularly.
🔗 Share this article