Search code examples
elasticsearch.net-coreconfigurationserilog

How to configure Serilog Elasticsearch error hanling in appsettings in .NET Core 3.1?


I am trying to configure Serilog in .NET Core 3.1 (C#) project, but I want to do that completely in appsettings.json. For file sinks I did all configuration w/o any problem, but for elasticsearch I can't figure out how to write rows belows into appsettings.json so that it works:

.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)
})

Official documentation shows just basic example for EmitEventFailure as follows:

"emitEventFailure": "WriteToSelfLog"

It doesn't show how combination (multiple flags) of EmitEventFailures should be written. Same situation for FailureSink:

"failureSink": "My.Namespace.MyFailureSink, My.Assembly.Name"

I don't know what exactly this means and I can't figure it out for code sample listed above.

Finally, for FailureCallback the documentation doesn't mention any option to do this through appsettings.json. But this option is not a big deal for me, at worst I can omit it.

Thanks for any hints!


Solution

  • After long hours of research on this, I came up with following answer.

    For "emitEventFailure" property, we only need to give comma between values like this:

    "emitEventFailure": "WriteToFailureSink, WriteToSelfLog, RaiseCallback",
    

    For the failureSink property, You can refer to this link for complex parameter value binding. We need to set the "type" of the object before specify each of parameters including the parameter's object. In my example is to set azure blob storage as the failure sink:

    "failureSink": {
            "type": "Serilog.Sinks.AzureBlobStorage.AzureBatchingBlobStorageSink, Serilog.Sinks.AzureBlobStorage",
            "blobServiceClient": {
              "type": "Azure.Storage.Blobs.BlobServiceClient, Azure.Storage.Blobs",
               "connectionString": "DefaultEndpointsProtocol=https;AccountName=xyz;AccountKey=xyzkey;EndpointSuffix=xyz.net"
            },
            "textFormatter": "Serilog.Formatting.Elasticsearch.ElasticsearchJsonFormatter, Serilog.Formatting.Elasticsearch",
            "storageContainerName": "test-api",
            "storageFileName": "test/{yyyy}-{MM}-{dd}.log",
            "period": "0.00:00:30",
            "batchSizeLimit": "1000"
            
          }