10

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>();
            });
}
rm5432
  • 327
  • 1
  • 3
  • 10
  • I agree with the accepted answer, but would like to add that your benchmark is flawed. The value of a benchmark where the web server is running everything in memory, doesn't connect to a database and doesn't send any HTTP request is close to nil. It's not even a comparison. It's like comparing nothing to something. – FantasticFiasco Mar 10 '21 at 18:47
  • Has it ever occurred to you that op is posting scenario that is small enough to fit into a stackoverflow page? A real world scenario is too big for readers to try to reproduce themselves. – Jason Cheng Jun 17 '21 at 18:26

1 Answers1

16

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.

C. Augusto Proiete
  • 24,684
  • 2
  • 63
  • 91
  • Why is writing to the console so slow? – Jason Cheng Jun 17 '21 at 18:24
  • 1
    @JasonCheng because writing to the console is supposedly a sequential blocking call even if there have been improvements in later versions of .net core https://weblog.west-wind.com/posts/2018/Dec/31/Dont-let-ASPNET-Core-Default-Console-Logging-Slow-your-App-down – GrahamB Oct 11 '21 at 15:25
  • Adding that single made things as fast as if logging was disabled . – aybe Mar 22 '22 at 09:45