Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version
  1. Install the Serilog.Sinks.Elasticsearch NuGet package in your project.
  2. Add the following code to your appsettings.json file:
"Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.Elasticsearch" ],
    "MinimumLevel": {
        "Default": "Debug",
        "Override": {
            "Microsoft": "Warning",
            "System": "Warning"
        }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
    "WriteTo": [
        {
            "Name": "Console"
        },
        {
            "Name": "Elasticsearch",
            "Args": {
                "nodeUris": "http://localhost:9200",
                "indexFormat": "logs-{0:yyyy.MM.dd}",
                "autoRegisterTemplate": true,
                "bufferBaseFilename": "serilog-buffer",
                "bufferFileSizeLimitBytes": 10240,
                "bufferLogShippingInterval": "00:00:10"
            }
        }
    ]
}
  1. Modify the nodeUris property with the endpoint of your Elasticsearch instance.
  2. Modify the indexFormat property to indicate the name of your index pattern.
  3. Modify any other properties as necessary.
  4. Add the following code to your application startup:
public static int Main(string[] args)
{
    var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();

    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(configuration)
        .CreateLogger();

    try
    {
        Log.Information("Starting up");
        CreateWebHostBuilder(args).Build().Run();
        return 0;
    }
    catch (Exception ex)
    {
        Log.Fatal(ex, "Application start-up failed");
        return 1;
    }
    finally
    {
        Log.CloseAndFlush();
    }
}

This code reads the configuration from the appsettings.json file and sets up the logger with the specified sinks. 7. Run your application and check the Elasticsearch instance for the logs.