I am trying to set Serilog's minimum level of calls using HttpClient to warning in a .Net 5 Blazor application using Serilog 2.10.0. It seems to work EFCore and other components but not HTTPClient - and I get info level quite verbose logging every time an HttpClient call is made.
The code in my Program.cs file looks like this.
public static void Main(string[] args)
{
// see https://nblumhardt.com/2019/10/serilog-in-aspnetcore-3/
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.MinimumLevel.Override("System.Net.Http.HttpClient", LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.File(new CompactJsonFormatter(), "Logs/log-.clef", rollingInterval: RollingInterval.Day)
.WriteTo.Console()
.CreateLogger();
Any suggestions on how to fix this would be greatly appreciated.
This is a bug, fixed in version 4.0.0, see:
https://github.com/serilog/serilog-aspnetcore/issues/221
An alternative is to use the ILogEventFilter:
public class MyLoggingFilter : ILogEventFilter
{
private static readonly HashSet<string> ignoredMessages = new HashSet<string>(StringComparer.Ordinal)
{
"Start processing HTTP request {HttpMethod} {Uri}",
"End processing HTTP request after {ElapsedMilliseconds}ms - {StatusCode}"
};
// Allow the event to be logged if the message template isn't one we ignore
public bool IsEnabled(LogEvent logEvent) => !ignoredMessages.Contains(logEvent.MessageTemplate.Text);
}
and:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.Filter.With<MyLoggingFilter>() // <-- Plug in your filter type
.Enrich.FromLogContext()
.WriteTo.File(new CompactJsonFormatter(), "Logs/log-.clef", rollingInterval: RollingInterval.Day)
.WriteTo.Console()
.CreateLogger();