I'have configured EventLog in my .Net Core 5.0 app to log application events to custom event log:
public Startup (IConfiguration configuration)
{
this.configuration = configuration;
this.logger = LoggerFactory.Create(logging=>{
logging.AddConsole();
logging.AddEventLog(settings=> {
settings.LogName = configuration["EventLogName"];
settings.SourceName = configuration["EventLogSourceName"];
settings.Filter = (category, level) => level >= LogLevel.Trace;
});
}).CreateLogger("Stage server logger");
}
My logging configuration in appsettings:
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
"EventLog": {
"LogLevel": {
"Default": "Information"
}
}
}
Everything works just fine but some messages (especialy unhandled exceptions) are written to "Application" log instead of configuration["EventLogName"] log. Any idea how to configure the app to log all messages from the application to configuration["EventLogName"] log? Thanks a lot
I see that you made an instance of the Logger
in your startup.cs
. I suppose you registered it in your DI? If yes, you don't see logs from all the sources because they are probably not using your Logger
instance. You're simply configuring a specific Logger
, not LoggerFactory
.
Could you try something like this in the program.cs
:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging((hostBuilder, logBuilder) => {
logBuilder.AddConsole();
logBuilder.AddEventLog(set => {
set.LogName = hostBuilder.Configuration["EventLogName"];
set.SourceName = hostBuilder.Configuration["EventLogSource"];
set.Filter = (category, level) => level >= LogLevel.Trace;
});
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
This way, I'm configuring Logger
also for the code that I'm not controlling - dependencies.
But if you want a minimal effort solution to fix just unhandled exceptions, the quick fix would be creating a middleware with try-catch and rethrow with logging exception by your specific Logger
injected by DI.