Serilog.Sinks.RabbitMQ 8.0.0

dotnet add package Serilog.Sinks.RabbitMQ --version 8.0.0                
NuGet\Install-Package Serilog.Sinks.RabbitMQ -Version 8.0.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Serilog.Sinks.RabbitMQ" Version="8.0.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Serilog.Sinks.RabbitMQ --version 8.0.0                
#r "nuget: Serilog.Sinks.RabbitMQ, 8.0.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Serilog.Sinks.RabbitMQ as a Cake Addin
#addin nuget:?package=Serilog.Sinks.RabbitMQ&version=8.0.0

// Install Serilog.Sinks.RabbitMQ as a Cake Tool
#tool nuget:?package=Serilog.Sinks.RabbitMQ&version=8.0.0                

serilog-sinks-rabbitmq

License

codecov Nuget Nuget

GitHub Release Date GitHub commits since latest release (by date) Size

GitHub contributors Activity Activity Activity

Run unit tests Publish preview to GitHub registry Publish release to Nuget registry CodeQL analysis

Purpose

This project is to allow Serilog to log to RabbitMQ using the RabbitMQ.Client package. The aim is to expose RabbitMQ.Client functionality, in a logical way, and not to build in additional logic into the sink. So expect pure RabbitMQ.Client behavior, but perhaps a little bit simpler interface.

Versioning

As of v3.0.0 we use Semantic Versioning to express changes in the API.

Dependencies

Serilog.Sinks.RabbitMQ .NETStandard .NETFramework Serilog RabbitMQ.Client
2.0.0 1.6.0 4.5.1 2.3.0 4.*
3.0.0 1.6.1 4.5.1 2.8.0 5.*
6.0.0 2.0.0 4.7.2 2.8.0 6.*
7.0.0 2.0.0 - 3.1.1 6.8.*
8.0.0 2.0.0 - 4.2.0 7.0

Installation

Using Nuget:

Install-Package Serilog.Sinks.RabbitMQ

Release Notes

See changelog.

Topics

Sink Configuration Options

The sink can be configured completely through code, by using configuration files (or other types of configuration providers), a combination of both, or by using the various Serilog configuration packages. The sink is configured with a typical Serilog WriteTo configuration method (or AuditTo, or similar variations).

All sink configuration methods accept the following arguments, though not necessarily in this order. Use of named arguments is strongly recommended.

  • hostnames
  • username
  • password
  • exchange
  • exchangeType
  • deliveryMode
  • routingKey
  • port
  • vHost
  • heartbeat
  • sslEnabled
  • sslServerName
  • sslVersion
  • sslAcceptablePolicyErrors
  • sslCheckCertificateRevocation
  • batchPostingLimit
  • bufferingTimeLimit
  • queueLimit
  • formatter
  • autoCreateExchange
  • maxChannels
  • levelSwitch

Arguments

Parameters exchange, exchangeType, deliveryMode, routingKey provide additional configuration when connecting to RabbitMQ. If autoCreateExchange is true, the sink will create the exchange if an exchange by that name doesn't exist. Exchange is not created by default.

If sslEnabled is true, the sink will use secure connection to server. By default, the server name is the same as the host name, no TLS version is specified, no server certificate errors are accepted, and certificate revocation checking is disabled. You can change server name through by setting the sslServerName, sslVersion, sslAcceptablePolicyErrors, sslCheckCertificateRevocation arguments.

This is a "periodic batching sink." The sink will queue a certain number of log events before they're actually written to RabbitMQ. There is also a timeout period so that the batch is always written even if it has not been filled. By default, the batch size is 50 rows and the timeout is 2 seconds. You can change these through by setting the batchPostingLimit and bufferingTimeLimit arguments.

Refer to the Formatter for details about the formatter arguments.

Code-Only (any .NET target)

All sink features are configurable from code. Here is a typical example that works the same way for any .NET target.

Log.Logger = new LoggerConfiguration()
    .Enrich.FromLogContext()
    .WriteTo.RabbitMQ(
        username: "usr",
        password: "pwd",
        hostnames: new[] { "localhost" },
        port: 5672,
        exchange = "LogExchange",
        formatter: new JsonFormatter()
    ).CreateLogger();

External configuration using Serilog.Settings.AppSettings

Refer to the Serilog.Settings.AppSettings package documentation for complete details about sink configuration. This is an example of setting some of the configuration parameters for this sink.

<add key="serilog:using:RabbitMQ" value="Serilog.Sinks.RabbitMQ"/>
<add key="serilog:write-to:RabbitMQ.username" value="user"/>
<add key="serilog:write-to:RabbitMQ.password" value="pwd"/>
<add key="serilog:write-to:RabbitMQ.hostnames" value="server1,server2"/>
<add key="serilog:write-to:RabbitMQ.exchange" value="LogExchange"/>
<add key="serilog:write-to:RabbitMQ.batchPostingLimit" value="1000"/>
<add key="serilog:write-to:RabbitMQ.bufferingTimeLimit" value="0.00:00:02.00"/>

External configuration using Serilog.Settings.Configuration

Refer to the Serilog.Settings.Configuration package documentation for complete details about sink configuration. Keys and values are not case-sensitive. This is an example of configuring the sink arguments.

{
  "Serilog": {
    "Using":  ["Serilog.Sinks.RabbitMQ"],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "RabbitMQ",
        "Args": {
          "username": "usr",
          "password": "pwd",
          "hostnames": [
            "localhost"
          ],
          "port": 5672,
          "exchange": "LogExchange",
          "autoCreateExchange": true,
          "batchPostingLimit": 1000,
          "bufferingTimeLimit": "0.00.00.02.00"
        } 
      }
    ]
  }
}

Audit Sink Configuration

A Serilog audit sink writes log events which are of such importance that they must succeed, and that verification of a successful write is more important than write performance. Unlike the regular sink, an audit sink does not fail silently - it can throw exceptions. You should wrap audit logging output in a try/catch block. The usual example is bank account withdrawal events - a bank would certainly not want to allow a failure to record those transactions to fail silently.

The constructor accepts most of the same arguments, and like other Serilog audit sinks, you configure one by using AuditTo instead of WriteTo.

  • hostnames
  • username
  • password
  • exchange
  • exchangeType
  • deliveryMode
  • routingKey
  • port
  • vHost
  • heartbeat
  • sslEnabled
  • sslServerName
  • sslVersion
  • sslAcceptablePolicyErrors
  • sslCheckCertificateRevocation
  • formatter
  • autoCreateExchange
  • maxChannels
  • levelSwitch

The batchPostingLimit and bufferingTimeLimit parameters are not available because the audit sink writes log events immediately.

{
  "Serilog": {
    "Using":  ["Serilog.Sinks.RabbitMQ"],
    "MinimumLevel": "Debug",
    "AuditTo": [
      {
        "Name": "RabbitMQ",
        "Args": {
          "username": "usr",
          "password": "pwd",
          "hostnames": [
            "localhost"
          ],
          "port": 5672,
          "exchange": "LogExchange",
          "autoCreateExchange": true
        }
      }
    ]
  }
}

Multihost Configuration

The sink can be configured taking multiple host names.
To keep the Serilog.Setting.ApSettings external configuration, additional hosts are added to the hostnames argument separated by commas. This is an example of configuring the multihost using Serilog.Settings.AppSettings.

<add key="serilog:using:RabbitMQ" value="Serilog.Sinks.RabbitMQ"/>
<add key="serilog:write-to:RabbitMQ.hostnames" value="host1,host2"/>
<add key="serilog:write-to:RabbitMQ.username" value="user"/>
<add key="serilog:write-to:RabbitMQ.pasword" value="pwd"/>

Use protected configuration (ASP.NET)

ASP.NET has the possibility to encrypt connection string in the web.config.

Configuration via code

There are multiple ways for configuring the RabbitMQSink with the release of v3.0.0

Log.Logger = new LoggerConfiguration()
    .Enrich.FromLogContext()
    .WriteTo.RabbitMQ((clientConfiguration, sinkConfiguration) =>
    {
        clientConfiguration.Username     = _config["RABBITMQ_USER"];
        clientConfiguration.Password     = _config["RABBITMQ_PASSWORD"];
        clientConfiguration.Exchange     = _config["RABBITMQ_EXCHANGE"];
        clientConfiguration.ExchangeType = _config["RABBITMQ_EXCHANGE_TYPE"];
        clientConfiguration.DeliveryMode = RabbitMQDeliveryMode.Durable;
        clientConfiguration.RoutingKey     = "Logs";
        clientConfiguration.Port         = 5672;

        foreach (string hostname in _config.GetSection("RABBITMQ_HOSTNAMES").Get<string[]>())
            clientConfiguration.Hostnames.Add(hostname);

        sinkConfiguration.TextFormatter  = new JsonFormatter();
    }).CreateLogger();
// Or
var config = new RabbitMQClientConfiguration
{
    Port            = 5672,
    DeliveryMode    = RabbitMQ.RabbitMQDeliveryMode.Durable,
    Exchange        = "test_exchange",
    Username        = "guest",
    Password        = "guest",
    ExchangeType    = "fanout"
};

foreach (string hostname in _config["RABBITMQ_HOSTNAMES"])
    config .Hostnames.Add(hostname);

Log.Logger = new LoggerConfiguration()
    .WriteTo.RabbitMQ((clientConfiguration, sinkConfiguration) =>
    {
        clientConfiguration.From(config);
        sinkConfiguration.TextFormatter = new JsonFormatter();
    }) .CreateLogger();
// Or
Log.Logger = new LoggerConfiguration()
    .WriteTo.RabbitMQ((clientConfiguration, sinkConfiguration) =>
    {
        clientConfiguration.From(Configuration.Bind("RabbitMQClientConfiguration", new RabbitMQClientConfiguration()));
        sinkConfiguration.TextFormatter = new JsonFormatter();
    }).CreateLogger();
// Or
LoggerConfiguration loggerConfiguration = new LoggerConfiguration();
IConfigurationSection rabbitMqSection = configuration.GetSection("log:rabbitMq");
loggerConfiguration = loggerConfiguration
    .WriteTo.RabbitMQ((clientConfiguration, sinkConfiguration) =>
    {
        rabbitMqSection.Bind(clientConfiguration);
        sinkConfiguration.RestrictedToMinimumLevel = LogEventLevel.Warning;
    });
// At last, don't forget to register the logger into the services
var loggerFactory = new LoggerFactory();
loggerFactory
  .AddSerilog() // if you are not assigning the logger to Log.Logger, then you need to add your logger here.
  .AddConsole(LogLevel.Information);

services.AddSingleton<ILoggerFactory>(loggerFactory);

Customizing Message Properties and Routing Keys

To customize message properties, a class can be created that implements the ISendMessageEvents interface. This interface defines two methods that require implementation:

OnSetMessageProperties: This method is invoked before the message is sent to RabbitMQ and is used to configure the message's properties.

OnGetRoutingKey: This method determines the routing key for the message, ensuring proper delivery to the intended queue.

Customize Message Properties and Routing Key

In order to set message properties, you can create a class which implements ISendMessageEvents. This interface describes two methods that you must implement. The first is OnSetMessageProperties which is called before the message is sent to RabbitMQ. The second is OnGetRoutingKey which is called to determine the routing key for the message.

public class CustomMessageEvents : ISendMessageEvents
{
    /// <inheritdoc />
    public void OnSetMessageProperties(LogEvent logEvent, IBasicProperties properties)
    {
        // example of setting message header based on log event level
        properties.Headers = new Dictionary<string, object?>
        {
            { "log-level", logEvent.Level.ToString() },
        };

        // example of setting correlation id based on log event properties
        if (logEvent.Properties.TryGetValue(LogProperties.CORRELATION_ID, out var correlationId))
        {
            properties.CorrelationId = correlationId.ToString();
        }
    }

    /// <inheritdoc />
    public string OnGetRoutingKey(LogEvent logEvent, string defaultRoutingKey)
    {
        // example of routing based on log level
        return logEvent.Level switch
        {
            LogEventLevel.Error => "error",
            _ => defaultRoutingKey
        };
    }
}

References

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (24)

Showing the top 5 NuGet packages that depend on Serilog.Sinks.RabbitMQ:

Package Downloads
Informatique.Base.Core

Base classed used in Project in Core

FFCEI.Microservices

A free library for ASP.NET Core 6+ Microservices development, with Model, Model Repository, Entity Framework Core and common Web Api features like CORS, Json serialization fixes, Swagger generation, JWT Authentication for simple and objective microservices development

Informatique.UOB.Base.Core

Base classed used in UOB Project in Core

Kalbe.Library.Common

Package Description

OKEService.EndPoints.Web

OK Micro Service EndPoints.Web Package

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
8.0.0 191 12/23/2024
7.0.3 2,748 11/24/2024
7.0.2 81,458 5/13/2024
7.0.1 47,052 3/19/2024
7.0.0 576 3/18/2024
7.0.0-pre.44 10,626 2/9/2024
6.0.0 1,470,106 1/23/2021
6.0.0-pre 40,992 10/4/2020
3.0.6 639,762 9/12/2019
3.0.3 17,303 7/5/2019
3.0.0 20,968 4/12/2019
2.0.2 230,352 4/25/2018
2.0.1 133,460 4/18/2017
2.0.0 4,443 10/18/2016
1.0.0.10 7,509 4/19/2016
1.0.0.6 1,475 4/15/2016
0.0.5.83 1,613 1/27/2016
0.0.5.79 2,011 11/3/2015
0.0.5.78 1,527 10/29/2015
0.0.5.77 1,462 10/29/2015