/NetCoreSeriLog

Serilog logging for ASP.NET Core

Primary LanguageC#

Serilog.AspNetCore

Serilog logging for ASP.NET Core. This package routes ASP.NET Core log messages through Serilog, so you can get information about ASP.NET's internal operations written to the same Serilog sinks as your application events.

With Serilog.AspNetCore installed and configured, you can write log messages directly through Serilog or any ILogger interface injected by ASP.NET. All loggers will use the same underlying implementation, levels, and destinations.

Instructions

First, install the following NuGet package into your app.

dotnet add package Serilog
dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Formatting.Elasticsearch
dotnet add package Serilog.Sinks.Elasticsearch

Then, add UseSerilog() to the Generic Host in CreateHostBuilder().

    
public static void Main(string[] args)
        {
            var cancellationTokenSource = new CancellationTokenSource();
            CreateWebHostBuilder(args, cancellationTokenSource).Build().Run();
            cancellationTokenSource.Cancel();
        }
    public static IWebHostBuilder CreateWebHostBuilder(string[] args,
    CancellationTokenSource cancellationTokenSource) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureLogging((_, config) => config.ClearProviders())
            .UseSerilog((_, configuration) =>
            {
                configuration
                    .MinimumLevel.Debug()
                    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                    .MinimumLevel.Override("System", LogEventLevel.Warning)
                    .Enrich.FromLogContext()
                    .Enrich.WithProperty("Application", "ModularApplication")
                    .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200"))
                    {
                        CustomFormatter = new ExceptionAsObjectJsonFormatter(renderMessage: true),
                        AutoRegisterTemplate = true,
                        TemplateName = "serilog-events-template",
                        IndexFormat = "hb-cms-log-{0:yyyy.MM.dd}"
                    });
            });
}