This is an ASP.NET Core 3.1 web application. I have Serilog request logging as described in https://nblumhardt.com/2019/10/serilog-in-aspnetcore-3/ and https://github.com/serilog/serilog-aspnetcore, and it works fine. The only problem is that it's also writing every HTTP request to the Windows Event Log, which is just making that worthless because now anytime I want to find exception information, the haystack has become huge.
My setup look like this. As you can see, I don't have the EventLog sink registered.
public static void Main(string[] args)
{
LoggerConfiguration loggerConfiguration = new LoggerConfiguration()
.Enrich.FromLogContext()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.WriteTo.Console(outputTemplate: LOG_TEMPLATE)
#if DEBUG
.WriteTo.Debug(outputTemplate: LOG_TEMPLATE)
#else
.WriteTo.File(new Serilog.Formatting.Compact.RenderedCompactJsonFormatter(), LOG_FILE_PATH)
#endif
;
Log.Logger = loggerConfiguration.CreateBootstrapLogger();
try
{
Log.Information("Starting up");
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application start-up failed");
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog((context, services, configuration) => configuration // 2-stage initialization so that we use the config values: https://github.com/serilog/serilog-aspnetcore
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
.WriteTo.Console(outputTemplate: LOG_TEMPLATE)
#if DEBUG
.WriteTo.Debug(outputTemplate: LOG_TEMPLATE)
#else
.WriteTo.File(new Serilog.Formatting.Compact.RenderedCompactJsonFormatter(), LOG_FILE_PATH)
#endif
, writeToProviders: true)
It turns out that if I have writeToProviders: true
set, then nothing gets written to the Event Log, but I actually need that because I have a custom ILogger
and ILoggerFactory
(we use JSNLog to log Javascript errors and write them to ELMAH), so I'm guessing there must be a default Microsoft sink that puts things in the Event Log or something.
Is there a way to work around this? Thanks in advance for your help.
It took a long time to finally figure this out, but the key was to go back through the Microsoft logging documentation and see that the logging component comes with four providers by default: console, debug, EventSource, and EventLog (when running on Windows), so when I used writeToProviders: true
, that caused my request logging to get pushed into the Event Log. The solution was to be sure and clear all the default providers, then re-add the Event Log one and set the minimum level to Warning.
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddEventLog(options =>
options.Filter((s, level) => level >= LogLevel.Warning));
}
.UseSerilog(...)
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