Very basic logging to console from netcore webapi with Serilog

Add serilog required packages

dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.ElasticSearch

Using

using Serilog;
using Serilog.Sinks.Elasticsearch;

Configure serilog on CreateHostBuilder. Only relevant code is included.

public class Program
{
    private const string ApplicationId = "Bustroker.Transactions.WebApi";
    private const string ElasticEndpoint = "http://localhost:9200";

    ///....
    ///....
    ///....
    ///....

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseSerilog((hostincContext, loggerConfiguration) => // send to Elastic for real time monitoring
                            ConfigureSerilogLoggerWithElastic(loggerConfiguration)
            )
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
    
    private static LoggerConfiguration ConfigureSerilogLoggerWithElastic(LoggerConfiguration loggerConfiguration)
    {
        var sinkOptions = new ElasticsearchSinkOptions(new Uri(ElasticEndpoint))
        {
            AutoRegisterTemplate = true,
            AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7,
            IndexFormat = $"{ApplicationId}-{0:yyyy.MM}"                                    
        };

        return loggerConfiguration
                    .MinimumLevel.Error()
                    .Enrich.FromLogContext()
                    .WriteTo.Elasticsearch(sinkOptions);
    }
}

Then add

// Startup.cs
 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseSerilogRequestLogging();

    ...
}

Now use it

[ApiController]
[Route("[controller]")]
public class OperationsController : ControllerBase
{
    private readonly ILogger<OpsController> _logger;

    public OperationsController(ILogger<OpsController> logger)
    {
        _logger = logger;
    }

    [HttpGet, Route("{currency}")]
    public async Task<IActionResult> Get(string currency)
    {
        _logger.LogInformation("Processed request /operations in '{currency}'", currency);
        return Ok(result);
    }
}

Use kibana to query the elastic. Otherwise, the API can be used instead.

Check the index has been created in elastic. Note that capital letters have been removed.

curl http://localhost:9200/bustroker.transactions.webapi-*

Query all the entries for the index

curl http://localhost:9200/bustroker.transactions.webapi-*/_search?q=*