LESSON 5 OF 12

5. Centralized Logging: Seq and the OTLP Log Approach

Set up Seq with Docker Compose, send Serilog events to a centralized destination, filter properties, investigate errors, use dashboards, and configure sinks securely.

75 dk 85

Introduction

In the previous lesson, we used console, file, and rolling file sinks to send log events to different destinations. That approach is useful during development, but searching logs individually on several servers, containers, or services becomes inefficient in production. Centralized logging collects application events in one shared destination so that searching, filtering, comparison, and incident investigation can be performed through a single interface.

In this lesson, Seq will be our centralized logging destination. We will run Seq with Docker Compose, send structured events from an ASP.NET Core application through the Serilog sink, and write property-based queries in Seq. We will also cover API keys, environment variables, secure configuration, and failure testing. By the end of the lesson, you will understand how the application behaves when the centralized destination is unavailable and why logging infrastructure must be tested like any other production dependency.

1. Seq and the centralized logging model

Seq is a server for storing and querying structured log events. A Serilog event is not limited to a rendered text message; it can contain a message template, timestamp, level, and properties such as Application, RequestId, OrderId, or CorrelationId. These properties make centralized searching much more useful.

For example, the following event stores the order identifier and elapsed time as separate fields:

Log.Information("Order completed for {OrderId} by {UserId} in {ElapsedMs} ms", orderId, userId, elapsedMs);

Instead of parsing the rendered message later, Seq can query OrderId, UserId, or ElapsedMs directly. This is especially valuable during error investigation and performance analysis.

Seq can provide its web interface and API from the same service. In a Docker deployment, application data should be mounted into a persistent volume outside the container. Otherwise, deleting and recreating the container can remove the event history and metadata.

2. Adding Seq with Docker Compose

Create a docker-compose.yml file in the project root. The following example exposes Seq on host port 5341 and mounts ./.docker/seq as persistent storage.

services:
  seq:
    image: datalust/seq:latest
    container_name: observability-seq
    restart: unless-stopped
    environment:
      ACCEPT_EULA: "Y"
      SEQ_FIRSTRUN_ADMINPASSWORD: "ChangeThisDevelopmentPassword!"
    ports:
      - "5341:80"
    volumes:
      - ./.docker/seq:/data

This example is convenient for a development environment. In a real team project, the password should not be written directly into the Compose file. Use Compose variables or a separate .env file, and make sure that the file is excluded from source control.

SEQ_ADMIN_PASSWORD=ChangeThisDevelopmentPassword!

Reference the variable from Compose:

environment:
  ACCEPT_EULA: "Y"
  SEQ_FIRSTRUN_ADMINPASSWORD: ${SEQ_ADMIN_PASSWORD}

Start the service with:

docker compose up -d seq
docker compose ps
docker compose logs seq

Open http://localhost:5341 in a browser. Sign in with the administrator account and inspect the Data or Settings areas. The Events screen may be empty until the application sends its first events.

3. Installing and configuring the Serilog Seq sink

Add the Seq sink package from the application directory:

dotnet add package Serilog.Sinks.Seq

Add Seq to the existing Serilog configuration. This example keeps the console and file destinations from the previous lessons while also enabling the centralized destination:

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .Enrich.FromLogContext()
    .Enrich.WithProperty("Application", "Orders.Api")
    .WriteTo.Console()
    .WriteTo.Seq(
        serverUrl: builder.Configuration["Seq:ServerUrl"]!,
        apiKey: builder.Configuration["Seq:ApiKey"])
    .CreateLogger();

If buffering is used, closing the logger during application shutdown is important so that pending events can be flushed:

try
{
    Log.Information("Application starting");
    app.Run();
}
finally
{
    Log.CloseAndFlush();
}

This lesson reads connection settings from configuration. The appsettings.json file can contain a non-secret local URL:

{
  "Seq": {
    "ServerUrl": "http://localhost:5341"
  }
}

Do not keep the API key in the file. Supply it through user secrets or an environment variable during development:

dotnet user-secrets init
dotnet user-secrets set "Seq:ApiKey" "your-development-api-key"

For an application running inside Docker Compose, hierarchical configuration keys can be supplied with double underscores:

Seq__ServerUrl=http://seq
Seq__ApiKey=your-api-key

Inside the Compose network, the application must not use the host's localhost to reach Seq. If the application also runs in Compose, use http://seq, where seq is the service name. If only Seq runs in a container and the application runs on the host, use http://localhost:5341.

4. Securing ingestion with an API key

Create an application-specific key from Data > Ingestion or Settings > API Keys in Seq. Separate keys for each application or environment make it easier to identify traffic and revoke access for only one source when necessary.

Choose a descriptive name such as orders-api-development. Depending on the ingestion policy, a key can also attach a fixed property to incoming events or filter events before they are stored. This can reduce unnecessary traffic to the central system. Never log the key itself, commit it to the repository, or reuse a development key in production.

During development, Serilog's internal diagnostic output can help identify sink problems:

Serilog.Debugging.SelfLog.Enable(message =>
{
    Console.Error.WriteLine(message);
});

SelfLog should be enabled only for temporary diagnosis. In production, uncontrolled output may expose connection details or other sensitive information, so it must be handled deliberately.

5. Searching and filtering properties in Seq

Generate a few example events from the application:

using (LogContext.PushProperty("CorrelationId", correlationId))
using (LogContext.PushProperty("TenantId", tenantId))
{
    logger.LogInformation("Loading order {OrderId}", orderId);
    logger.LogWarning("Payment retry for {OrderId} with attempt {Attempt}", orderId, attempt);
}

On the Seq Events screen, expand an event to view its properties. You can use the filtering controls beside properties or enter expressions such as these:

GoalSeq query
Events from one applicationApplication = 'Orders.Api'
Find one orderOrderId = 'ORD-1001'
List errors@Level = 'Error'
Find slow operationsElapsedMs > 1000
Trace one correlation IDCorrelationId = 'corr-123'
Errors for an endpoint@Level = 'Error' and RequestPath = '/api/orders'

Sending a named property is better than concatenating the property into the message because it preserves searchability and analytical value. Prefer "Order {OrderId} failed" to "Order " + orderId + " failed".

6. Investigating errors and building a basic dashboard

Use a consistent investigation sequence. First narrow the time range, then filter by Application, Environment, RequestPath, and CorrelationId. Open an error event and inspect the exception type, stack trace, and other events carrying the same correlation value.

Frequently used queries can be saved as signals. For example, create an Errors signal from @Level = 'Error' and a Slow Requests signal from ElapsedMs > 1000. A dashboard can then contain basic charts for event counts, endpoint distribution, or error trends over time.

Do not fill dashboards with unlimited, expensive queries. Prefer focused signals. Selecting signals can reduce the event area that Seq must search and can improve search and dashboard performance. A useful first dashboard contains:

  • The number of errors during the last 24 hours.
  • Error distribution by endpoint or service.
  • The change in slow requests over time.

7. Testing a centralized logging failure

Do not assume that the centralized destination will always be available. Stop the Seq container and send a request to the application:

docker compose stop seq

Observe the following behavior:

  • Does the HTTP request fail because the application cannot send a log to Seq?
  • Do console or file sinks continue to receive events?
  • Do memory or thread usage increase?
  • Does Serilog SelfLog report connection errors?

A sink failure should not normally stop the application's primary business workflow. However, buffering, retry, and failure-handling behavior depends on the sink and its configuration, so it must be tested rather than assumed. For critical events, consider local fallback, container stdout, or a collector layer. When event volume is high, also monitor buffering, retry behavior, and disk consumption.

Restart Seq and verify recovery:

docker compose start seq
curl http://localhost:5341/health

This test validates more than connectivity. It helps define expectations for event loss, delay, and recovery after an outage.

8. How Seq relates to the OTLP log approach

The Serilog sink sends events directly to Seq's ingestion API. OTLP is a standard protocol for transporting logs, traces, and metrics between exporters, collectors, and telemetry backends. These approaches are not necessarily alternatives. An application can produce events through Serilog while a collector routes telemetry through OTLP to one or more backends. Seq can also be part of an observability architecture that receives OTLP log and trace data when configured for that purpose.

In this lesson, we use Serilog.Sinks.Seq because it gives us a direct path to Seq's search and dashboard features. In later lessons, we will add OpenTelemetry tracing and metrics and examine the boundaries between instrumentation, exporters, collectors, and backends. The important distinction is that a sink is an integration between a logging framework and a destination, while OTLP is a transport protocol for telemetry data.

Short practice exercise

  1. Start Seq with Docker Compose and verify the persistent volume.
  2. Add the Serilog.Sinks.Seq package.
  3. Read Seq:ServerUrl and Seq:ApiKey from a secure configuration source.
  4. Emit events from an endpoint with CorrelationId, OrderId, and ElapsedMs properties.
  5. Find information, warning, and error events with the same correlation ID.
  6. Create one signal for errors and another for slow requests.
  7. Stop Seq, observe the application, then restart Seq and verify recovery.

Common mistakes

  • Using localhost inside a container: Applications on the Compose network should use the Seq service name.
  • Writing the API key to appsettings.json: Use user secrets, environment variables, or a secure secret store.
  • Omitting the volume: Recreating the container can remove the event history.
  • Writing everything at Information level: Noise and storage costs increase; choose levels according to purpose.
  • Concatenating properties into strings: Centralized filtering and searching become weaker.
  • Not testing sink failures: Try network interruptions, incorrect URLs, and invalid API keys deliberately.
  • Exposing Seq directly to the Internet: Configure authentication, TLS, firewall rules, and ingestion policies before production.

Conclusion

In this lesson, we centralized Serilog events in Seq, ran Seq with Docker Compose and persistent storage, and configured secure ingestion with an API key. Structured properties allowed us to query meaningful event fields rather than relying only on rendered messages. We also created a basic signal and dashboard strategy for errors and slow requests.

Finally, we tested the behavior of the system when the centralized destination was unavailable. This demonstrated that observability infrastructure is itself an operational system that requires failure testing, recovery expectations, and security controls. In the next lesson, we will connect logs with traces and metrics to understand how requests move across services.

Sources