asp.net-coreelasticsearchserilog

How to configure Elastic.Serilog.Sinks 8.11 in ASP.NET Core 8 web app?


I used Serilog.Sinks.Elasticsearch 10.0 package but it has been deprecated now. But I don't how to configure recommended package Elastic.Serilog.Sinks 8.11. Please help me.

Current code:

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Information()
    .Enrich.FromLogContext()
    .WriteTo.Console(Serilog.Events.LogEventLevel.Information)
    .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(Configuration["ElasticPath"]))
    {
        ModifyConnectionSettings = x => x.BasicAuthentication("username", "password"),
        AutoRegisterTemplate = true,
        AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv8,
        IndexFormat = $"projectx-{Configuration["Environment"]}-{DateTime.UtcNow:yyyy-MM}",
        BatchAction = ElasticOpType.Create,
        TypeName = null,
        FailureCallback = (e, ex) => Console.WriteLine("Unable to submit event " + e.MessageTemplate),
        EmitEventFailure = EmitEventFailureHandling.WriteToSelfLog |
                         EmitEventFailureHandling.WriteToFailureSink |
                         EmitEventFailureHandling.RaiseCallback
    })
    .CreateLogger();

This sample code block but I didn't set authentication and index name:

Log.Logger = new LoggerConfiguration()
     .MinimumLevel.Debug()
     .Enrich.FromLogContext()
     .WriteTo.Console(Serilog.Events.LogEventLevel.Information)
     .WriteTo.Elasticsearch([new Uri(Configuration["ElasticPath"])], opts =>
                {
                    opts.BootstrapMethod = Elastic.Ingest.Elasticsearch.BootstrapMethod.Failure;
                    opts.DataStream = new Elastic.Ingest.Elasticsearch.DataStreams.DataStreamName("logs", "generic");
                    opts.ConfigureChannel = channelOpts => {
                        channelOpts.BufferOptions = new BufferOptions { ExportMaxConcurrency = 10 };                        
                    };
                })
     .CreateLogger();

Solution

  • To add authentication like before, you can do this way :

    Log.Logger = new LoggerConfiguration()
     .MinimumLevel.Debug()
     .Enrich.FromLogContext()
     .WriteTo.Console(Serilog.Events.LogEventLevel.Information)
     .WriteTo.Elasticsearch([new Uri(Configuration["ElasticPath"])], opts =>
     {
         opts.BootstrapMethod = Elastic.Ingest.Elasticsearch.BootstrapMethod.Failure;
         opts.DataStream = new Elastic.Ingest.Elasticsearch.DataStreams.DataStreamName("logs", "generic");
         opts.ConfigureChannel = channelOpts => {
             channelOpts.BufferOptions = new BufferOptions { ExportMaxConcurrency = 10 };
         };
     }, transport =>
     {
        transport.Authentication(new BasicAuthentication(username, password));
     })
     .CreateLogger();