I am using SeriLog(with Loki sink), and I also have an Exception handler lambda
-like in here, which catches all exceptions happened during code execution and logs them with appropriate labels.
But, Serilog itself, automatically catches all unhandled exceptions and logs them before me. As a result, an exception is being logged twice.
How can I disable Serilog's automatic logging? This is my current Serilog Config:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging((logging) =>
{
var log = new LoggerConfiguration()
.MinimumLevel.Debug()
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
logging.AddSerilog(log);
});
I followed this GitHub issue. The problem is that, both my own logging middleware and Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware logs the same exception.
The solution is to disable ExceptionHandlerMiddleware
. And I've done it by https://github.com/serilog/serilog-expressions like:
new LoggerConfiguration().Filter.ByExcluding("SourceContext <> 'Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware'")
Final code:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.Loki;
namespace MyNameSpace
{
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.Filter.ByExcluding("SourceContext = 'Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware'")
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.LokiHttp(new NoAuthCredentials("http://localhost:3100"))
.CreateLogger();
try
{
Log.Information("Starting web host");
CreateHostBuilder(args).Build().Run();
return;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
return;
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}