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>();
});
}
Serilog is a structured logging library for . NET with more features and better performance than the built-in Microsoft logging libraries, but the standard console sink is still slow.
From the official site:https://serilog.net/, "Serilog provides diagnostic logging to files, the console, and elsewhere. It is easy to set up, has a clean API, and is portable between recent . NET platforms. Unlike other logging libraries, Serilog is built with powerful structured event data in mind."
Serilog provides sinks for writing log events to storage in various formats. Many of the sinks listed below are developed and supported by the wider Serilog community; please direct questions and issues to the relevant repository. More sinks can be found by searching within the serilog tag on NuGet.
Since Serilog supports ASP.NET Cores default logging APIs it can receive log events from ASP.NET Core framework libraries as well. Serilog in ASP.NET Core is very easy to set up and integrate. Serilog provides a structured logging framework and supports a wide variety of sinks to log to console, files, azure, etc.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With