khellang / Middleware

Various ASP.NET Core middleware
MIT License
811 stars 112 forks source link

ProblemDetailsMiddleware and DiagnosticListener.Write for handled exceptions #193

Open dungimon opened 1 year ago

dungimon commented 1 year ago

I'm using your library along with ElasticAPM and the unfortunate combination of both is causing all my handled exceptions to be logged in elastic. I only want unhandled exceptions to be logged so actual exceptions that need attention aren't lost in the noise. Unfortunately the app I work on throws and handles more exceptions that I'd like, and the likelihood of a system wide refactoring anytime soon is unlikely.

The culprit is line 126 of Hellang.Middleware.ProblemDetails.ProblemDetailsMiddleware:

private const string DiagnosticListenerKey = "Microsoft.AspNetCore.Diagnostics.HandledException";
......        
if (DiagnosticListener.IsEnabled() && DiagnosticListener.IsEnabled(DiagnosticListenerKey))
{
    DiagnosticListener.Write(DiagnosticListenerKey, new { httpContext = context, exception = error });
}

Because the elastic apm automatically adds the AspNetCoreErrorDiagnosticsSubscriber (non-negotiable) then the IsEnabled always returns true and the diagnostic write is always executed.

Is there a workaround for this? or is there scope for this library to accomodate this and allow for this to be toggled on/off? thanks!