LESSON 4 OF 12

4. Sinks: Console, File, and Rolling File

Configure Serilog console, file, and rolling file destinations with JSON formatting, size limits, retention, rotation, and environment-specific settings.

50 dk 92

Introduction

In Serilog, a sink is the component that determines where a log event is written. The console sink sends events to standard output, the file sink persists events on disk, and rolling file configuration creates new files according to time or file size. Sink selection is not merely an implementation detail. Readable console output is useful during development, while production systems require controlled file growth, retention policies, and machine-readable formats.

In this lesson, we will add the required NuGet packages and configure console and file destinations in the same ASP.NET Core application. We will then implement daily rolling files, file-size limits, retention, JSON formatting, and environment-specific sink selection. Finally, we will test rotation behavior and review common operational mistakes.

1. Understanding the sink architecture

The Serilog pipeline is straightforward: the application creates a log event, the logger evaluates minimum levels and filters, and accepted events are sent to one or more sinks. The same event can be written to both the console and a file. This allows different consumers to receive different representations of the same operational information.

SinkSuitable useAdvantageConsideration
ConsoleLocal development and container stdoutImmediate visibility and easy debuggingDoes not provide durable storage by itself
FileLocal or single-host persistenceSimple and fast archivingDisk permissions and capacity must be managed
Rolling FileDaily or size-based file managementKeeps files within operational limitsA retention policy must be defined

The file sink applies default limits for file size and retained files. In production, those limits should be selected deliberately to prevent uncontrolled disk usage and to align with the organization’s log retention policy.

2. Installing the packages

Run the following commands from the directory containing the ASP.NET Core project. If the Serilog ASP.NET Core integration was completed in the previous lesson, only the missing sink packages need to be added.

dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.File
dotnet add package Serilog.Formatting.Compact
dotnet add package Serilog.Settings.Configuration

Serilog.Sinks.Console provides the console destination, Serilog.Sinks.File provides file output, and Serilog.Formatting.Compact provides compact JSON formatting. Serilog.Settings.Configuration allows sink settings to be read from appsettings.json.

3. Configuring console and file sinks in code

We will begin by configuring the pipeline directly in Program.cs. This approach is useful when you want to see sink parameters explicitly in C# and establish a working baseline quickly.

File: src/Observability.Api/Program.cs

using Serilog;
using Serilog.Formatting.Compact;

Log.Logger = new LoggerConfiguration()
    .Enrich.FromLogContext()
    .Enrich.WithProperty("Application", "Observability.Api")
    .WriteTo.Console(
        outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} <s:{SourceContext}>{NewLine}{Exception}")
    .WriteTo.File(
        path: "Logs/app-.log",
        rollingInterval: RollingInterval.Day,
        retainedFileCountLimit: 14,
        fileSizeLimitBytes: 10 * 1024 * 1024,
        rollOnFileSizeLimit: true,
        shared: false,
        buffered: false)
    .WriteTo.File(
        new CompactJsonFormatter(),
        path: "Logs/app-json-.log",
        rollingInterval: RollingInterval.Day,
        retainedFileCountLimit: 14,
        fileSizeLimitBytes: 25 * 1024 * 1024,
        rollOnFileSizeLimit: true);

try
{
    Log.Information("Starting application");

    var builder = WebApplication.CreateBuilder(args);
    builder.Host.UseSerilog();
    builder.Services.AddControllers();

    var app = builder.Build();
    app.MapControllers();
    app.Run();
}
catch (Exception exception)
{
    Log.Fatal(exception, "Application failed to start");
}
finally
{
    Log.CloseAndFlush();
}

In this example, an event can be written to both file sinks. The first file uses a human-readable text template. The second uses JSON, which is easier for log collectors and search tools to process. Log.CloseAndFlush() helps ensure that buffered events are flushed when the application shuts down.

4. Rolling file options

Daily rotation

The dash in path: "Logs/app-.log" allows the rolling file sink to add date information to the file name. With RollingInterval.Day, files are created in a form such as app-20261103.log. Hourly and minute-based rotation can be enabled with RollingInterval.Hour and RollingInterval.Minute. Very frequent rotation increases the number of files, so it should be reserved for high-volume workloads or short-lived tests.

File-size limits

fileSizeLimitBytes specifies an approximate upper bound for a file. When rollOnFileSizeLimit: true is enabled, a new numbered file is created after the limit is reached within the same time interval. When daily and size-based policies are combined, files may appear with suffixes such as app-20261103_001.log.

Retention

retainedFileCountLimit restricts the number of retained files. The current file may be included in this count. Although null can be used for unlimited retention, production systems should only do this when disk capacity, archiving, and centralized logging policies have been considered. A count limit can also be combined with retainedFileTimeLimit for time-based cleanup.

5. JSON formatting and configuration files

Managing the file sink from configuration rather than code makes deployment-time changes easier. Shared settings can be placed in appsettings.json, while environment-specific values can be supplied by appsettings.Development.json or appsettings.Production.json.

File: src/Observability.Api/appsettings.json

{
  "Serilog": {
    "Using": [
      "Serilog.Sinks.Console",
      "Serilog.Sinks.File"
    ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information",
        "System": "Warning"
      }
    },
    "Enrich": [ "FromLogContext" ],
    "Properties": {
      "Application": "Observability.Api"
    },
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} <s:{SourceContext}>{NewLine}{Exception}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/app-.log",
          "rollingInterval": "Day",
          "retainedFileCountLimit": 14,
          "fileSizeLimitBytes": 10485760,
          "rollOnFileSizeLimit": true
        }
      }
    ]
  }
}

File: src/Observability.Api/Program.cs

using Serilog;

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSerilog((context, services, configuration) =>
    configuration
        .ReadFrom.Configuration(context.Configuration)
        .ReadFrom.Services(services)
        .Enrich.FromLogContext());

builder.Services.AddControllers();

var app = builder.Build();
app.MapControllers();
app.Run();

ASP.NET Core loads an environment-specific appsettings.{ENVIRONMENT}.json file, and values from that file can override values from the base file. This makes it possible to keep a readable console and short-lived file sink in Development while using only console output or a centralized sink in Production.

6. Selecting sinks by environment

Different environments do not always need the same destinations. Console plus a short-retention file is convenient locally. In containerized production, leaving events on stdout and allowing the platform or collector to forward them may be more appropriate.

File: src/Observability.Api/appsettings.Development.json

{
  "Serilog": {
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/development-.log",
          "rollingInterval": "Day",
          "retainedFileCountLimit": 3,
          "fileSizeLimitBytes": 5242880,
          "rollOnFileSizeLimit": true
        }
      }
    ]
  }
}

File: src/Observability.Api/appsettings.Production.json

{
  "Serilog": {
    "WriteTo": [
      { "Name": "Console" }
    ]
  }
}

To set the environment explicitly, for example on Linux or macOS, run ASPNETCORE_ENVIRONMENT=Development dotnet run. If you write files in production, verify that the application identity has permission to write to the Logs directory and that the directory is located on durable storage when required.

7. Testing readability and rotation

Test endpoint

Let us add a small controller that writes events at different levels.

File: src/Observability.Api/Controllers/LogTestController.cs

using Microsoft.AspNetCore.Mvc;

namespace Observability.Api.Controllers;

[ApiController]
[Route("api/log-test")]
public sealed class LogTestController : ControllerBase
{
    private readonly ILogger<LogTestController> _logger;

    public LogTestController(ILogger<LogTestController> logger)
    {
        _logger = logger;
    }

    [HttpGet]
    public IActionResult Get()
    {
        _logger.LogInformation("Test request received: {Path}", HttpContext.Request.Path);
        _logger.LogWarning("Example warning: {RemainingQuota}", 12);
        return Ok(new { status = "logged" });
    }
}
  1. Start the application with dotnet run.
  2. Call curl http://localhost:5000/api/log-test several times.
  3. Check the console for the timestamp, level, and SourceContext values.
  4. Open the text and, if configured, JSON files under the Logs directory.
  5. To observe rotation quickly, reduce fileSizeLimitBytes in the development configuration to a value such as 1024.
  6. Send enough requests to produce files with suffixes such as _001 and _002.
  7. Reduce the retention limit to two and restart the application to observe cleanup of older files.

When checking the JSON file, verify that each line represents one valid JSON event. A log analysis tool may expect line-delimited JSON, and multiline exception rendering can affect how a parser interprets the output.

8. Common mistakes

  • Missing package: If WriteTo.File() is configured without installing Serilog.Sinks.File, the application may fail during configuration.
  • Wrong directory assumption: A relative path such as Logs/app-.log is resolved from the working directory. A service or container may use a different working directory than your local shell.
  • No retention policy: Allowing files to grow indefinitely can fill the disk and prevent the application from writing further logs.
  • Manual file deletion: Moving or deleting the active file externally while the application is running can produce platform-dependent behavior. Prefer the sink’s rolling policy.
  • Verbose production logging: Debug or Verbose levels can create significant disk and CPU overhead under high traffic.
  • Multiple processes: If multiple processes must write to the same file, evaluate whether shared: true is required and understand its operational cost.
  • Sensitive data: Never write tokens, passwords, connection strings, or personal data to files without proper masking and policy controls.

9. Short practice exercise

Task: Configure the application for two environments. In Development, use console plus a daily rolling file with a 2 MB file limit and a maximum of five retained files. Add compact JSON formatting. In Production, keep only a JSON console sink. Then send at least 20 requests and test file rotation in Development.

A successful solution should verify the following: Is the environment-specific file actually loaded? Does the selected minimum level show the expected events? Are old files removed according to the retention limit? Is the JSON output valid and suitable for line-based processing?

Conclusion

In this lesson, we used the Serilog sink architecture in a practical ASP.NET Core application. The console sink provided immediate visibility, the file sink provided durable local output, and rolling file settings kept rotation under control. We configured daily files, size limits, retention, JSON formatting, and environment-specific destinations.

The next step is to combine these sinks with correlation IDs, request logging, and centralized log collection. The key principle is that observability is not only about producing events. Events must also be routed to the right destination, serialized in a useful format, and retained through a sustainable operational policy.

Sources