Serilog.Sinks.LogStream

Logo

📡🪵 A Serilog sink that writes events to a LogStream server.

View the Project on GitHub guibranco/serilog-sinks-logstream

Serilog.Sinks.LogStream

📡🪵 A Serilog sink that writes events to a LogStream server.

GitHub license Time tracker

Serilog.Sinks.LogStream logo

Documentation: GitHub Pages


Table of content


Features


CI/CD

Build and tests Release Last commit
Build and Test Release GitHub last commit

Code Quality

codecov


.NET support

Target framework Supported
.NET Standard 2.0 (.NET Framework 4.6.2+, .NET Core 2.0+) ✅
.NET 8.0 ✅
.NET 9.0 ✅
.NET 10.0 ✅

Requires Serilog 4 or later.


Installation

GitHub Releases

GitHub last release GitHub All Releases

Download the latest .nupkg from the Releases page.

NuGet package manager

Package Version Downloads
Serilog.Sinks.LogStream Serilog.Sinks.LogStream NuGet Version Serilog.Sinks.LogStream NuGet Downloads
dotnet add package Serilog.Sinks.LogStream

Usage

File storage

The server has one shared API_SECRET; name the application with appKey:

Log.Logger = new LoggerConfiguration()
    .WriteTo.LogStream(
        serverUrl: "https://logs.example.com",
        appId: "production",
        appKey: "billing-api",
        apiSecret: Environment.GetEnvironmentVariable("LOGSTREAM_API_SECRET"))
    .CreateLogger();

MariaDB storage

Each application has its own key and token (X-Api-Key / X-Api-Token); the key is the app key:

Log.Logger = new LoggerConfiguration()
    .WriteTo.LogStream(
        serverUrl: "https://logs.example.com",
        appId: "production",
        apiKey: "billing-api",
        apiToken: Environment.GetEnvironmentVariable("LOGSTREAM_API_TOKEN"))
    .CreateLogger();

UDP

For high-volume logging the server can also take HMAC-signed UDP datagrams (UDP_PORT, default 8082/udp), which skip the TCP handshake, TLS and HTTP parsing. Set transport to Udp; the same credentials sign every packet (apiToken, or apiSecret in file storage), and the secret never travels on the wire:

Log.Logger = new LoggerConfiguration()
    .WriteTo.LogStream(
        serverUrl: "https://logs.example.com",
        appId: "production",
        apiKey: "billing-api",
        apiToken: Environment.GetEnvironmentVariable("LOGSTREAM_API_TOKEN"),
        transport: LogStreamTransport.Udp,
        udpPort: 8082) // the host defaults to the host of serverUrl; set udpHost to override it
    .CreateLogger();

Each event becomes one datagram, still batched by Serilog before sending. UDP is fire-and-forget: the server never replies, so lost, rejected (stale clock, unknown key, source IP not allowed…) or dropped packets are not reported to the sink — check udp.rejected in the server’s GET /api/health. Keep clocks NTP-synced: packets must arrive within ±30 s of the server’s time.

Events too large for one datagram (UdpMaxPacketSize, default 8192 bytes, the server’s UDP_MAX_PACKET_SIZE) — typically ones with long stack traces — are posted over HTTP instead, so serverUrl stays required. Set UdpFallbackToHttp = false to drop them (reported to SelfLog).

[!IMPORTANT] Call Log.CloseAndFlush() (or dispose the logger) on shutdown so buffered events are sent.

appsettings.json

With Serilog.Settings.Configuration:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.LogStream" ],
    "MinimumLevel": "Information",
    "WriteTo": [
      {
        "Name": "LogStream",
        "Args": {
          "serverUrl": "https://logs.example.com",
          "appId": "production",
          "apiKey": "billing-api",
          "apiToken": "lss_…",
          "batchSizeLimit": 100,
          "period": "00:00:02"
        }
      }
    ]
  }
}

Keep the secret or token out of source control (user secrets, environment variables such as Serilog__WriteTo__0__Args__apiToken, or a vault).

Arguments

Argument Default Description
serverUrl — Base address of the server, e.g. https://logs.example.com
appId — Instance or environment identifier (app_id)
appKey null Application slug (app_key); required with apiSecret
apiSecret null Shared write secret (file storage)
apiKey null Client key (MariaDB storage), sent as X-Api-Key
apiToken null Client token (MariaDB storage), sent as X-Api-Token
restrictedToMinimumLevel Verbose Minimum level passed through the sink
batchSizeLimit 100 Events per request (at most 1000)
period 00:00:02 Longest wait before a partial batch is sent
queueLimit 100000 Events buffered in memory; null for no limit
retryTimeLimit 10 minutes How long a failing batch is retried before it is dropped
categoryPropertyName SourceContext Property that becomes the entry category
levelSwitch null Switch to change the minimum level at runtime
formatProvider invariant culture Culture used to render messages
messageHandler null HTTP message handler for the sink’s client (e.g. a proxy)
transport Http Http, or Udp for signed, fire-and-forget datagrams
udpHost host of serverUrl Host that receives UDP datagrams
udpPort 8082 UDP port (the server’s UDP_PORT)

UdpMaxPacketSize (default 8192) and UdpFallbackToHttp (default true) are set through the options overload below.

Full options

Log.Logger = new LoggerConfiguration()
    .Enrich.FromLogContext()
    .WriteTo.LogStream(
        o =>
        {
            o.ServerUrl = new Uri("https://logs.example.com");
            o.ApiKey = "billing-api";
            o.ApiToken = token;
            o.AppId = builder.Environment.EnvironmentName;
            o.StaticContext["region"] = "eu-west-1";
            o.HttpClient = httpClientFactory.CreateClient("logstream"); // optional
        },
        batching =>
        {
            batching.BatchSizeLimit = 200;
            batching.BufferingTimeLimit = TimeSpan.FromSeconds(1);
            batching.RetryTimeLimit = TimeSpan.FromMinutes(2);
        })
    .CreateLogger();

[!WARNING] LogStream is meant for back-end services: don’t log to it from browser or mobile front ends, where the credentials would be exposed.


What is sent

LogStream field Taken from
level Verbose, Debug → debug; Information → info; Warning → warning; Error → error; Fatal → critical
category The SourceContext property (the ForContext<T>() logger name), or CategoryPropertyName; general when missing. Truncated to 100 characters
message The rendered message (invariant culture unless formatProvider is set)
message_template The message template text, so LogStream groups every event from the same line (IncludeMessageTemplate)
context StaticContext, then every event property as JSON ({@Object} structures keep their shape and a $type tag), span_id, and exception
context.exception type, message, stack_trace, source and inner_exception (or inner_exceptions for an AggregateException)
trace_id The event’s trace ID (Serilog 4 captures Activity.Current); without one, the server generates one per entry
timestamp The event timestamp, in UTC
app_key, app_id, batch_id The options, and a new GUID per request
User-Agent header {entry assembly}/{version} (Serilog.Sinks.LogStream/{version}), or UserAgent

Over UDP each datagram is {"v":1,"key":…,"ts":…,"nonce":…,"sig":…,"log":{…}}: key is apiKey (or appKey), ts the send time in Unix milliseconds, nonce 16 random bytes as hex, and sig the hex HMAC-SHA256(secret, "{key}:{ts}:{nonce}:{log}") over the exact log text. log holds the fields above plus app_id, batch_id (shared by the events of one Serilog batch) and user_agent.


Batching and failures

The sink uses Serilog’s built-in batching (BatchingOptions):

Argument Default Description
batchSizeLimit 100 Events per request (at most 1000, the server’s limit)
period 2 s Longest wait before a partial batch is sent
queueLimit 100,000 Events kept in memory; newer ones are dropped while full
retryTimeLimit 10 min How long a failing batch is retried before it is dropped

Network errors, timeouts and HTTP 408, 429 and 5xx are retried with back-off. Other rejections (400, 401, 403…) are reported to SelfLog and the batch is dropped, because sending it again would fail the same way. Entries the server rejects one by one (the errors list of a 201/202 response) are reported to SelfLog too.

Over UDP, only a failure to resolve the host (or of the HTTP fallback for oversized events, which is sent first) is retried. Datagrams the OS refuses to send are reported to SelfLog and dropped rather than retried, so an event is never sent twice.

Serilog.Debugging.SelfLog.Enable(Console.Error);

Project Description
logstream-server The ingestion and streaming server
logstream-ui The dashboard
CrispyWaffle.LogStream The LogStream log provider for the CrispyWaffle toolkit

Building

dotnet build
dotnet test
dotnet csharpier check .

Support

If you need help, feel free to open an issue.


Contributing

Contributions are welcome! Fork the repository, create a branch, and open a pull request. Please run dotnet csharpier format . and make sure dotnet test passes before submitting.


Contributors

Thanks to all contributors! 💙

guibranco
Guilherme Branco Stracini

Bots

dependabot[bot]
dependabot[bot]
github-actions[bot]
github-actions[bot]
snyk-bot
Snyk bot

License

This project is licensed under the MIT License.