• This repository has been archived on 01/Jun/2024
  • Stars
    star
    434
  • Rank 100,274 (Top 2 %)
  • Language
    C#
  • License
    Apache License 2.0
  • Created over 9 years ago
  • Updated 6 months ago

Reviews

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

Repository Details

A Serilog sink that writes events to Elasticsearch

Serilog.Sinks.Elasticsearch Continuous Integration NuGet Badge

This repository contains two nuget packages: Serilog.Sinks.Elasticsearch and Serilog.Formatting.Elasticsearch.

Just a heads up that the .NET team @elastic have created their own new Serilog Sink called Elastic.Serilog.Sinks (Package: https://www.nuget.org/packages/Elastic.Serilog.Sinks#readme-body-tab and documentation: https://www.elastic.co/guide/en/ecs-logging/dotnet/current/serilog-data-shipper.html). Althought this current sink will still work, I advice you to have a look first at the official Elastic implementation as it is better supported and more up to date.

Table of contents

What is this sink

The Serilog Elasticsearch sink project is a sink (basically a writer) for the Serilog logging framework. Structured log events are written to sinks and each sink is responsible for writing it to its own backend, database, store etc. This sink delivers the data to Elasticsearch, a NoSQL search engine. It does this in a similar structure as Logstash and makes it easy to use Kibana for visualizing your logs.

Features

  • Simple configuration to get log events published to Elasticsearch. Only server address is needed.
  • All properties are stored inside fields in ES. This allows you to query on all the relevant data but also run analytics over this data.
  • Be able to customize the store; specify the index name being used, the serializer or the connections to the server (load balanced).
  • Durable mode; store the logevents first on disk before delivering them to ES making sure you never miss events if you have trouble connecting to your ES cluster.
  • Automatically create the right mappings for the best usage of the log events in ES or automatically upload your own custom mapping.
  • Starting from version 3, compatible with Elasticsearch 2.
  • Version 6.x supports the new Elasticsearch.net version 6.x library.
  • From version 8.x there is support for Elasticsearch.net version 7.
  • From version 9.x there is support for Elasticsearch.net version 8. Version detection is enabled by default, in which case TypeName is handled automatically across major versions 6, 7 and 8. Versions 2 and 5 of Elasticsearch are no longer supported. Version 9.0.0 of the sink targets netstandard2.0 and therefore can be run on any .NET Framework that supports it (both .NET Core and .NET Framework), however, we are focused on testing it with .NET 6.0 to make the maintenance simpler.

Quick start

Elasticsearch sinks

Install-Package serilog.sinks.elasticsearch

Simplest way to register this sink is to use default configuration:

var loggerConfig = new LoggerConfiguration()
    .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200")));

Or, if using .NET Core and Serilog.Settings.Configuration Nuget package and appsettings.json, default configuration would look like this:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Elasticsearch" ],
    "MinimumLevel": "Warning",
    "WriteTo": [
      {
        "Name": "Elasticsearch",
        "Args": {
          "nodeUris": "http://localhost:9200"
        }
      }
    ]
  }
}

More elaborate configuration, using additional Nuget packages (e.g. Serilog.Enrichers.Environment) would look like:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Elasticsearch" ],
    "MinimumLevel": "Warning",
    "WriteTo": [
      {
        "Name": "Elasticsearch",
        "Args": {
          "nodeUris": "http://localhost:9200"
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName" ],
    "Properties": {
      "Application": "My app"
    }
  }
}

This way the sink will detect version of Elasticsearch server (DetectElasticsearchVersion is set to true by default) and handle TypeName behavior correctly, based on the server version (6.x, 7.x or 8.x).

Disable detection of Elasticsearch server version

Alternatively, DetectElasticsearchVersion can be set to false and certain option can be configured manually. In that case, the sink will assume version 7 of Elasticsearch, but options will be ignored due to a potential version incompatibility.

For example, you can configure the sink to force registeration of v6 index template. Be aware that the AutoRegisterTemplate option will not overwrite an existing template.

var loggerConfig = new LoggerConfiguration()
    .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200") ){
             DetectElasticsearchVersion = false,
             AutoRegisterTemplate = true,
             AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6
     });

Configurable properties

Besides a registration of the sink in the code, it is possible to register it using appSettings reader (from v2.0.42+) reader (from v2.0.42+) as shown below.

This example shows the options that are currently available when using the appSettings reader.

  <appSettings>
    <add key="serilog:using" value="Serilog.Sinks.Elasticsearch"/>
    <add key="serilog:write-to:Elasticsearch.nodeUris" value="http://localhost:9200;http://remotehost:9200"/>
    <add key="serilog:write-to:Elasticsearch.indexFormat" value="custom-index-{0:yyyy.MM}"/>
    <add key="serilog:write-to:Elasticsearch.templateName" value="myCustomTemplate"/>
    <add key="serilog:write-to:Elasticsearch.typeName" value="myCustomLogEventType"/>
    <add key="serilog:write-to:Elasticsearch.pipelineName" value="myCustomPipelineName"/>
    <add key="serilog:write-to:Elasticsearch.batchPostingLimit" value="50"/>
    <add key="serilog:write-to:Elasticsearch.batchAction" value="Create"/><!-- "Index" is default -->
    <add key="serilog:write-to:Elasticsearch.period" value="2"/>
    <add key="serilog:write-to:Elasticsearch.inlineFields" value="true"/>
    <add key="serilog:write-to:Elasticsearch.restrictedToMinimumLevel" value="Warning"/>
    <add key="serilog:write-to:Elasticsearch.bufferBaseFilename" value="C:\Temp\SerilogElasticBuffer"/>
    <add key="serilog:write-to:Elasticsearch.bufferFileSizeLimitBytes" value="5242880"/>
    <add key="serilog:write-to:Elasticsearch.bufferLogShippingInterval" value="5000"/>
    <add key="serilog:write-to:Elasticsearch.bufferRetainedInvalidPayloadsLimitBytes" value="5000"/>
    <add key="serilog:write-to:Elasticsearch.bufferFileCountLimit " value="31"/>
    <add key="serilog:write-to:Elasticsearch.connectionGlobalHeaders" value="Authorization=Bearer SOME-TOKEN;OtherHeader=OTHER-HEADER-VALUE" />
    <add key="serilog:write-to:Elasticsearch.connectionTimeout" value="5" />
    <add key="serilog:write-to:Elasticsearch.emitEventFailure" value="WriteToSelfLog" />
    <add key="serilog:write-to:Elasticsearch.queueSizeLimit" value="100000" />
    <add key="serilog:write-to:Elasticsearch.autoRegisterTemplate" value="true" />
    <add key="serilog:write-to:Elasticsearch.autoRegisterTemplateVersion" value="ESv7" />
    <add key="serilog:write-to:Elasticsearch.detectElasticsearchVersion" value="false" /><!-- `true` is default -->
    <add key="serilog:write-to:Elasticsearch.overwriteTemplate" value="false" />
    <add key="serilog:write-to:Elasticsearch.registerTemplateFailure" value="IndexAnyway" />
    <add key="serilog:write-to:Elasticsearch.deadLetterIndexName" value="deadletter-{0:yyyy.MM}" />
    <add key="serilog:write-to:Elasticsearch.numberOfShards" value="20" />
    <add key="serilog:write-to:Elasticsearch.numberOfReplicas" value="10" />
    <add key="serilog:write-to:Elasticsearch.formatProvider" value="My.Namespace.MyFormatProvider, My.Assembly.Name" />
    <add key="serilog:write-to:Elasticsearch.connection" value="My.Namespace.MyConnection, My.Assembly.Name" />
    <add key="serilog:write-to:Elasticsearch.serializer" value="My.Namespace.MySerializer, My.Assembly.Name" />
    <add key="serilog:write-to:Elasticsearch.connectionPool" value="My.Namespace.MyConnectionPool, My.Assembly.Name" />
    <add key="serilog:write-to:Elasticsearch.customFormatter" value="My.Namespace.MyCustomFormatter, My.Assembly.Name" />
    <add key="serilog:write-to:Elasticsearch.customDurableFormatter" value="My.Namespace.MyCustomDurableFormatter, My.Assembly.Name" />
    <add key="serilog:write-to:Elasticsearch.failureSink" value="My.Namespace.MyFailureSink, My.Assembly.Name" />
  </appSettings>

With the appSettings configuration the nodeUris property is required. Multiple nodes can be specified using , or ; to separate them. All other properties are optional. Also required is the <add key="serilog:using" value="Serilog.Sinks.Elasticsearch"/> setting to include this sink. All other properties are optional. If you do not explicitly specify an indexFormat-setting, a generic index such as 'logstash-[current_date]' will be used automatically.

And start writing your events using Serilog.

Elasticsearch formatters

Install-Package serilog.formatting.elasticsearch

The Serilog.Formatting.Elasticsearch nuget package consists of a several formatters:

  • ElasticsearchJsonFormatter - custom json formatter that respects the configured property name handling and forces Timestamp to @timestamp.
  • ExceptionAsObjectJsonFormatter - a json formatter which serializes any exception into an exception object.

Override default formatter if it's possible with selected sink

var loggerConfig = new LoggerConfiguration()
  .WriteTo.Console(new ElasticsearchJsonFormatter());

More information

A note about fields inside Elasticsearch

Be aware that there is an explicit and implicit mapping of types inside an Elasticsearch index. A value called X as a string will be indexed as being a string. Sending the same X as an integer in a next log message will not work. ES will raise a mapping exception, however it is not that evident that your log item was not stored due to the bulk actions performed.

So be careful about defining and using your fields (and type of fields). It is easy to miss that you first send a {User} as a simple username (string) and next as a User object. The first mapping dynamically created in the index wins. See also issue #184 for details and a possible solution. There are also limits in ES on the number of dynamic fields you can actually throw inside an index.

A note about Kibana

In order to avoid a potentially deeply nested JSON structure for exceptions with inner exceptions, by default the logged exception and it's inner exception is logged as an array of exceptions in the field exceptions. Use the 'Depth' field to traverse the inner exceptions flow.

However, not all features in Kibana work just as well with JSON arrays - for instance, including exception fields on dashboards and visualizations. Therefore, we provide an alternative formatter, ExceptionAsObjectJsonFormatter, which will serialize the exception into the exception field as an object with nested InnerException properties. This was also the default behavior of the sink before version 2.

To use it, simply specify it as the CustomFormatter when creating the sink:

    new ElasticsearchSink(new ElasticsearchSinkOptions(url)
    {
      CustomFormatter = new ExceptionAsObjectJsonFormatter(renderMessage:true)
    });

JSON appsettings.json configuration

To use the Elasticsearch sink with Microsoft.Extensions.Configuration, for example with ASP.NET Core or .NET Core, use the Serilog.Settings.Configuration package. First install that package if you have not already done so:

Install-Package Serilog.Settings.Configuration

Instead of configuring the sink directly in code, call ReadFrom.Configuration():

var configuration = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json")
    .Build();

var logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration)
    .CreateLogger();

In your appsettings.json file, under the Serilog node, :

{
  "Serilog": {
    "WriteTo": [{
        "Name": "Elasticsearch",
        "Args": {
          "nodeUris": "http://localhost:9200;http://remotehost:9200/",
          "indexFormat": "custom-index-{0:yyyy.MM}",
          "templateName": "myCustomTemplate",
          "typeName": "myCustomLogEventType",
          "pipelineName": "myCustomPipelineName",
          "batchPostingLimit": 50,
          "batchAction": "Create",
          "period": 2,
          "inlineFields": true,
          "restrictedToMinimumLevel": "Warning",
          "bufferBaseFilename":  "C:/Temp/docker-elk-serilog-web-buffer",
          "bufferFileSizeLimitBytes": 5242880,
          "bufferLogShippingInterval": 5000,
          "bufferRetainedInvalidPayloadsLimitBytes": 5000,
          "bufferFileCountLimit": 31,
          "connectionGlobalHeaders" :"Authorization=Bearer SOME-TOKEN;OtherHeader=OTHER-HEADER-VALUE",
          "connectionTimeout": 5,
          "emitEventFailure": "WriteToSelfLog",
          "queueSizeLimit": "100000",
          "autoRegisterTemplate": true,
          "autoRegisterTemplateVersion": "ESv2",
          "overwriteTemplate": false,
          "registerTemplateFailure": "IndexAnyway",
          "deadLetterIndexName": "deadletter-{0:yyyy.MM}",
          "numberOfShards": 20,
          "numberOfReplicas": 10,
          "templateCustomSettings": [{ "index.mapping.total_fields.limit": "10000000" } ],
          "formatProvider": "My.Namespace.MyFormatProvider, My.Assembly.Name",
          "connection": "My.Namespace.MyConnection, My.Assembly.Name",
          "serializer": "My.Namespace.MySerializer, My.Assembly.Name",
          "connectionPool": "My.Namespace.MyConnectionPool, My.Assembly.Name",
          "customFormatter": "My.Namespace.MyCustomFormatter, My.Assembly.Name",
          "customDurableFormatter": "My.Namespace.MyCustomDurableFormatter, My.Assembly.Name",
          "failureSink": "My.Namespace.MyFailureSink, My.Assembly.Name"
        }
    }]
  }
}

See the XML <appSettings> example above for a discussion of available Args options.

Handling errors

From version 5.5 you have the option to specify how to handle issues with Elasticsearch. Since the sink delivers in a batch, it might be possible that one or more events could actually not be stored in the Elasticsearch store. Can be a mapping issue for example. It is hard to find out what happened here. There is a new option called EmitEventFailure which is an enum (flagged) with the following options:

  • WriteToSelfLog, the default option in which the errors are written to the SelfLog.
  • WriteToFailureSink, the failed events are send to another sink. Make sure to configure this one by setting the FailureSink option.
  • ThrowException, in which an exception is raised.
  • RaiseCallback, the failure callback function will be called when the event cannot be submitted to Elasticsearch. Make sure to set the FailureCallback option to handle the event.

An example:

.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200"))
                {
                    FailureCallback = e => Console.WriteLine("Unable to submit event " + e.MessageTemplate),
                    EmitEventFailure = EmitEventFailureHandling.WriteToSelfLog |
                                       EmitEventFailureHandling.WriteToFailureSink |
                                       EmitEventFailureHandling.RaiseCallback,
                    FailureSink = new FileSink("./failures.txt", new JsonFormatter(), null)
                })

With the AutoRegisterTemplate option the sink will write a default template to Elasticsearch. When this template is not there, you might not want to index as it can influence the data quality. Since version 5.5 you can use the RegisterTemplateFailure option. Set it to one of the following options:

  • IndexAnyway; the default option, the events will be send to the server
  • IndexToDeadletterIndex; using the deadletterindex format, it will write the events to the deadletter queue. When you fix your template mapping, you can copy your data into the right index.
  • FailSink; this will simply fail the sink by raising an exception.

Since version 7 you can specify an action to do when log row was denied by the elasticsearch because of the data (payload) if durable file is specied. i.e.

BufferCleanPayload = (failingEvent, statuscode, exception) =>
                    {
                        dynamic e = JObject.Parse(failingEvent);
                        return JsonConvert.SerializeObject(new Dictionary<string, object>()
                        {
                            { "@timestamp",e["@timestamp"]},
                            { "level","Error"},
                            { "message","Error: "+e.message},
                            { "messageTemplate",e.messageTemplate},
                            { "failingStatusCode", statuscode},
                            { "failingException", exception}
                        });
                    },

The IndexDecider didnt worked well when durable file was specified so an option to specify BufferIndexDecider is added. Datatype of logEvent is string i.e.

 BufferIndexDecider = (logEvent, offset) => "log-serilog-" + (new Random().Next(0, 2)),

Option BufferFileCountLimit is added. The maximum number of log files that will be retained. including the current log file. For unlimited retention, pass null. The default is 31. Option BufferFileSizeLimitBytes is added The maximum size, in bytes, to which the buffer log file for a specific date will be allowed to grow. By default 100L * 1024 * 1024 will be applied.

Breaking changes

Version 9

  • Dropped support for 456 and sticking now with NETSTANDARD
  • Dropped support for Opensearch - This package supported writing to Opensearch (without guarantees) up untill the last version, Updated ES packages dropped support for Opensearch

Version 7

  • Nuget Serilog.Sinks.File is now used instead of deprecated Serilog.Sinks.RollingFile
  • SingleEventSizePostingLimit option is changed from int to long? with default value null, Don't use value 0 nothing will be logged then!!!!!

Version 6

Starting from version 6, the sink has been upgraded to work with Elasticsearch 6.0 and has support for the new templates used by ES 6.

If you use the AutoRegisterTemplate option, you need to set the AutoRegisterTemplateVersion option to ESv6 in order to generate default templates that are compatible with the breaking changes in ES 6.

Version 4

Starting from version 4, the sink has been upgraded to work with Serilog 2.0 and has .NET Core support.

Version 3

Starting from version 3, the sink supports the Elasticsearch.Net 2 package and Elasticsearch version 2. If you need Elasticsearch 1.x support, then stick with version 2 of the sink. The function

protected virtual ElasticsearchResponse<T> EmitBatchChecked<T>(IEnumerable<LogEvent> events)

now uses a generic type. This allows you to map to either DynamicResponse when using Elasticsearch.NET or to BulkResponse if you want to use NEST.

We also dropped support for .NET 4 since the Elasticsearch.NET client also does not support this version of the framework anymore. If you need to use .net 4, then you need to stick with the 2.x version of the sink.

Version 2

Be aware that version 2 introduces some breaking changes.

  • The overloads have been reduced to a single Elasticsearch function in which you can pass an options object.
  • The namespace and function names are now Elasticsearch instead of ElasticSearch everywhere
  • The Exceptions recorded by Serilog are customer serialized into the Exceptions property which is an array instead of an object.
  • Inner exceptions are recorded in the same array but have an increasing depth parameter. So instead of nesting objects you need to look at this parameter to find the depth of the exception.
  • Do no longer use the mapping once provided in the Gist. The Sink can automatically create the right mapping for you, but this feature is disabled by default. We advice you to use it.
  • Since version 2.0.42 the ability to register this sink using the AppSettings reader is restored. You can pass in a node (or collection of nodes) and optionally an indexname and template.

More Repositories

1

serilog-sinks-applicationinsights

A Serilog sink that writes events to Microsoft Azure Application Insights
C#
219
star
2

serilog-ui

Simple Serilog log viewer UI for several sinks.
C#
207
star
3

serilog-sinks-grafana-loki

A Serilog sink sending log events to Grafana Loki
C#
188
star
4

Serilog.Enrichers.Sensitive

A Serilog LogEvent enricher that masks sensitive data
C#
112
star
5

serilog-sinks-richtextbox

A Serilog sink that writes log events to a WPF RichTextBox control with colors and theme support
C#
97
star
6

serilog-enrichers-clientinfo

Enrich logs with client IP, correlation id and HTTP request headers.
C#
90
star
7

serilog-sinks-graylog

Serilog sink for graylog
C#
81
star
8

serilog-sinks-notepad

A Serilog sink that writes log events to Notepad as text or JSON
C#
61
star
9

Serilog.Sinks.Postgresql.Alternative

Serilog.Sinks.Postgresql.Alternative is a library to save logging information from https://github.com/serilog/serilog to https://www.postgresql.org/.
C#
59
star
10

SerilogSinksInMemory

In-memory sink for Serilog to use for testing
C#
53
star
11

serilog-sinks-splunk

A Serilog sink that writes to Splunk
C#
45
star
12

serilog-sinks-slack

A simple (yet customizable) Slack logging sink for Serilog
C#
41
star
13

serilog-sinks-azuretablestorage

A Serilog sink that writes events to Azure Table Storage
C#
40
star
14

serilog-sinks-sentry

A Sentry sink for Serilog
C#
36
star
15

Serilog.Sinks.Telegram.Alternative

Serilog.Sinks.Telegram.Alternative is a library to save logging information from Serilog to Telegram.
C#
35
star
16

Serilog.Sinks.MicrosoftTeams.Alternative

Serilog.Sinks.MicrosoftTeams.Alternative is a library to save logging information from Serilog to Microsoft Teams.
C#
30
star
17

serilog-sinks-slackclient

Slack Sink for Serilog
C#
27
star
18

serilog-diagnostics-tracelistener

A System.Diagnostics.TraceListener that writes trace data into Serilog
C#
25
star
19

serilog-enrichers-globallogcontext

A Serilog Enricher for adding properties to all log events in your app
C#
25
star
20

Serilog.Sinks.AmazonS3

Serilog.Sinks.AmazonS3 is a library to save logging information from Serilog to Amazon S3. The idea there was to upload log files to Amazon S3 to later evaluate them with Amazon EMR services.
C#
21
star
21

serilog-sinks-teams

A Serilog event sink that writes to Microsoft Teams
C#
18
star
22

Serilog-Sinks-Discord

Serilog discord sink
C#
17
star
23

Serilog.Sinks.Network

A serilog network sink. Designed with logstash and the Elastic stack in mind
C#
16
star
24

home

This is the hub for all the projects that are part of the Serilog Contrib Organization
16
star
25

Serilog.Sinks.Logz.Io

C#
16
star
26

serilog-sinks-exceldnalogdisplay

A Serilog sink that writes events to Excel-DNA LogDisplay
C#
13
star
27

serilog-sinks-azureeventhub

A Serilog sink that writes events to Azure EventHubs
C#
13
star
28

serilog-sinks-rollbar

A Serilog sink which writes events to Rollbar
C#
10
star
29

Serilog.Logfmt

Simple Serilog formatter to output Logfmt
C#
9
star
30

serilog-enrichers-exceldna

A Serilog Enricher with properties from Excel-DNA add-ins
C#
6
star
31

serilog-enrichers-memory

An enricher for Serilog which outputs memory usage
C#
6
star
32

serilog-sinks-apachekafka

A sink for Serilog that writes events to Kafka
C#
6
star
33

serilog-sinks-msbuild

An MSBuild sink for Serilog.
C#
5
star
34

serilog-settings-xml

Xml file based configuration for Serilog (https://serilog.net)
C#
5
star
35

serilog-sinks-OnePageSink

Sink that displays real-time messages from Serilog in a separate web page. Uses SignalR as a transport. Stores nothing, uses no memory. If you refresh your page you will lose your messages
C#
4
star
36

serilog-formatting-log4net

Format Serilog events in log4net or log4j compatible XML format
C#
4
star
37

Serilog.Sinks.DelegatingText

A Serilog sink to emit formatted log events to a delegate.
C#
3
star
38

brand

Guide and reference to designers, writers, and developers to create consistent, on-brand content for Serilog
2
star
39

serilog-sinks-youtrack

A Serilog sink that writes events to YouTrack
C#
2
star
40

Serilog.Enrichers.ActivityTags

C#
1
star
41

Serilog.Sinks.Logcat

Android logcat sink extension for the Serilog logger
C#
1
star
42

Serilog.Enrichers.ApplicationName

PowerShell
1
star
43

serilog-sinks-amqp-batching

C#
1
star
44

serilog-settings-xml2

A Serilog settings provider that reads from XML sources with zero dependencies and full configuration support
C#
1
star