Search code examples
asp.net-coreserilog

Serilog slow, bad performance


Am I doing something wrong or Serilog has awful performance?

Create a new Asp.Net Core 5.0 webapi project, add a reference to Serilog.AspNetCore nuget package and the following configuration code. Serilogs adds 15ms per request! In my maching jumps from 5ms to 20ms in a release build.

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .Enrich.FromLogContext()
            .WriteTo.Console()
            .CreateLogger();

        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseSerilog()
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Solution

  • The performance hit is likely not Serilog itself, but the fact that you're writing all logs to the Console synchronously, which blocks the request thread and will have some impact on performance.

    If you were using any other logging library that ends up calling Console.WriteLine I'd expect you to get similar perf. results.

    A common pattern is to use the Async sink, and write to the Console on a background thread. E.g.:

    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
        .Enrich.FromLogContext()
        .WriteTo.Async(writeTo => writeTo.Console()) // <<#<<#<<
        .CreateLogger();
    

    Of course, writing directly to the Console from a web app is usually not the best approach... There are much better Sinks you can use to target directly the place(s) where you'll store your logs.