• Stars
    star
    231
  • Rank 173,434 (Top 4 %)
  • Language
    C#
  • License
    Apache License 2.0
  • Created over 8 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An asynchronous wrapper for Serilog sinks that logs on a background thread

Serilog.Sinks.Async Build status NuGet Join the chat at https://gitter.im/serilog/serilog

An asynchronous wrapper for other Serilog sinks. Use this sink to reduce the overhead of logging calls by delegating work to a background thread. This is especially suited to non-batching sinks like the File and RollingFile sinks that may be affected by I/O bottlenecks.

Note: many of the network-based sinks (CouchDB, Elasticsearch, MongoDB, Seq, Splunk...) already perform asynchronous batching natively and do not benefit from this wrapper.

Getting started

Install from NuGet:

Install-Package Serilog.Sinks.Async

Assuming you have already installed the target sink, such as the file sink, move the wrapped sink's configuration within a WriteTo.Async() statement:

Log.Logger = new LoggerConfiguration()
    .WriteTo.Async(a => a.File("logs/myapp.log"))
    // Other logger configuration
    .CreateLogger()

Log.Information("This will be written to disk on the worker thread");

// At application shutdown (results in monitors getting StopMonitoring calls)
Log.CloseAndFlush();

The wrapped sink (File in this case) will be invoked on a worker thread while your application's thread gets on with more important stuff.

Because the memory buffer may contain events that have not yet been written to the target sink, it is important to call Log.CloseAndFlush() or Logger.Dispose() when the application exits.

Buffering & Dropping

The default memory buffer feeding the worker thread is capped to 10,000 items, after which arriving events will be dropped. To increase or decrease this limit, specify it when configuring the async sink. One can determine whether events have been dropped via Serilog.Async.IAsyncLogEventSinkInspector.DroppedMessagesCount (see Sink State Inspection interface below).

// Reduce the buffer to 500 events
.WriteTo.Async(a => a.File("logs/myapp.log"), bufferSize: 500)

Health Monitoring via the Monitor and Inspector interfaces

The Async wrapper is primarily intended to allow one to achieve minimal logging latency at all times, even when writing to sinks that may momentarily block during the course of their processing (e.g., a File Sink might block for a low number of ms while flushing). The dropping behavior is an important failsafe; it avoids having an unbounded buffering behaviour should logging throughput overwhelm the sink, or the sink ingestion throughput degrade.

In practice, this configuration (assuming one provisions an adequate bufferSize) achieves an efficient and resilient logging configuration that can safely handle load without impacting processing throughput. The risk is of course that events get be dropped if the buffer threshold gets breached. The inspection interface, IAsyncLogEventSinkInspector (obtained by providing an IAsyncLogEventSinkMonitor when configuring the Async Sink), enables a health monitoring mechanism to actively validate that the buffer allocation is not being exceeded in practice.

// Example check: log message to an out of band alarm channel if logging is showing signs of getting overwhelmed
void ExecuteAsyncBufferCheck(IAsyncLogEventSinkInspector inspector)
{
    var usagePct = inspector.Count * 100 / inspector.BufferSize;
    if (usagePct > 50) SelfLog.WriteLine("Log buffer exceeded {0:p0} usage (limit: {1})", usagePct, inspector.BufferSize);
}

class MonitorConfiguration : IAsyncLogEventSinkMonitor
{
    public void StartMonitoring(IAsyncLogEventSinkInspector inspector) =>
        HealthMonitor.AddPeriodicCheck(() => ExecuteAsyncBufferCheck(inspector));

    public void StopMonitoring(IAsyncLogEventSinkInspector inspector) 
    { /* reverse of StartMonitoring */ }
}

// Provide monitor so we can wire the health check to the inspector
var monitor = new MonitorConfiguration();
// Use default config (drop events if >10,000 backlog)
.WriteTo.Async(a => a.File("logs/myapp.log"), monitor: monitor) ...

Blocking

Warning: For the same reason one typically does not want exceptions from logging to leak into the execution path, one typically does not want a logger to be able to have the side-effect of actually interrupting application processing until the log propagation has been unblocked.

When the buffer size limit is reached, the default behavior is to drop any further attempted writes until the queue abates, reporting each such failure to the Serilog.Debugging.SelfLog. To replace this with a blocking behaviour, set blockWhenFull to true.

// Wait for any queued event to be accepted by the `File` log before allowing the calling thread to resume its
// application work after a logging call when there are 10,000 LogEvents awaiting ingestion by the pipeline
.WriteTo.Async(a => a.File("logs/myapp.log"), blockWhenFull: true)

XML <appSettings> and JSON configuration

Using Serilog.Settings.Configuration JSON:

{
  "Serilog": {
    "WriteTo": [{
      "Name": "Async",
      "Args": {
        "configure": [{
          "Name": "Console"
        }]
      }
    }]
  }
}

XML configuration support has not yet been added for this wrapper.

About this sink

This sink was created following this conversation thread: serilog/serilog#809.

More Repositories

1

serilog

Simple .NET logging with fully-structured events
C#
7,150
star
2

serilog-aspnetcore

Serilog integration for ASP.NET Core
C#
1,306
star
3

serilog-settings-configuration

A Serilog configuration provider that reads from Microsoft.Extensions.Configuration
C#
443
star
4

serilog-sinks-file

Write Serilog events to files in text and JSON formats, optionally rolling on time or size
C#
331
star
5

serilog-extensions-logging

Serilog provider for Microsoft.Extensions.Logging
C#
312
star
6

serilog-sinks-console

Write log events to System.Console as text or JSON, with ANSI theme support
C#
240
star
7

serilog-expressions

An embeddable mini-language for filtering, enriching, and formatting Serilog events, ideal for use with JSON or XML configuration.
C#
187
star
8

serilog-sinks-mssqlserver

A Serilog sink that writes events to Microsoft SQL Server
C#
169
star
9

serilog-extensions-logging-file

Add file logging to ASP.NET Core apps in one line of code.
C#
154
star
10

serilog-formatting-compact

Compact JSON event format for Serilog
C#
153
star
11

serilog-extensions-hosting

Serilog logging for Microsoft.Extensions.Hosting
C#
139
star
12

serilog-sinks-opentelemetry

A Serilog OpenTelemetry Protocol (OTLP) sink
C#
116
star
13

serilog-filters-expressions

Expression-based event filtering for Serilog
C#
80
star
14

serilog-enrichers-environment

Enrich Serilog log events with properties from System.Environment.
C#
77
star
15

serilog-sinks-email

A Serilog sink that writes events to SMTP email
C#
72
star
16

serilog-sinks-periodicbatching

Infrastructure for Serilog sinks that process events in batches.
C#
70
star
17

serilog-sinks-browserconsole

A console sink for the Blazor/Wasm environment
C#
61
star
18

serilog-sinks-rollingfile

Deprecated: new applications should use https://github.com/serilog/serilog-sinks-file instead
C#
60
star
19

serilog-sinks-xamarin

A Serilog sink that writes events to Xamarin mobile targets
C#
54
star
20

serilog-sinks-eventlog

A Serilog sink that writes events to the Windows Event Log
C#
50
star
21

serilog-settings-appsettings

An <appSettings> configuration reader for Serilog
C#
50
star
22

serilog-enrichers-thread

Enrich Serilog events with properties from the current thread.
C#
46
star
23

serilog-sinks-map

A Serilog sink wrapper that dispatches events based on a property value
C#
41
star
24

serilog-sinks-debug

Writes Serilog events to the debug output window
C#
35
star
25

serilog-formatting-compact-reader

A reader for Serilog's compact JSON format
C#
32
star
26

serilog-sinks-loggly

A Serilog event sink that writes to Loggly
C#
27
star
27

serilog-enrichers-process

The process enricher for Serilog.
C#
26
star
28

serilog-sinks-observable

Write Serilog events to observers (Rx) through an IObservable
C#
23
star
29

serilog-sinks-azuredocumentdb

A Serilog sink that writes to Azure DocumentDB
C#
17
star
30

serilog-sinks-amazonkinesis

A Serilog sink that logs to Amazon Kinesis
C#
14
star
31

serilog-sinks-signalr

A Serilog sink that writes events to SignalR
C#
14
star
32

serilog-sinks-log4net

A Serilog sink that writes events to log4net
C#
13
star
33

serilog-sinks-trace

The diagnostic trace sink for Serilog.
C#
11
star
34

serilog-sinks-coloredconsole

Deprecated: now a part of https://github.com/serilog/serilog-sinks-console
C#
10
star
35

serilog-sinks-datadog

A Serilog sink that writes events to DataDog
C#
9
star
36

serilog-sinks-logentries

A Serilog sink that writes events to Logentries
C#
8
star
37

serilog-sinks-nlog

A Serilog sink that writes events to NLog
C#
8
star
38

serilog-sinks-textwriter

The System.IO.TextWriter sink for Serilog
C#
8
star
39

serilog-generator

A simulation that generates simple log data through Serilog, ideal for testing sinks or log servers
C#
6
star
40

serilog-sinks-rethinkdb

A Serilog sink that writes to RethinkDB
C#
5
star
41

serilog-sinks-xsockets

A Serilog sink that writes events to XSockets
C#
4
star
42

serilog-sinks-reflectinsight

Writes events from Serilog to the ReflectInsight logging framework
C#
3
star
43

serilog-dnx-prerelease

Pre-release support for the DNX (.NET 5) runtime environment for Serilog
C#
3
star
44

serilog-sinks-dynamodb

A Serilog sink that writes events to Amazon Web Services DynamoDB
C#
1
star