I would like to use the .NET Core Logger in an ExceptionFilter like this:
public class GlobalExceptionAttribute : ExceptionFilterAttribute
{
private readonly ILogger<Inspection> _logger;
public GlobalExceptionAttribute(ILogger<Inspection> logger)
{
_logger = logger;
}
public override void OnException(ExceptionContext context)
{
_logger.LogError("Error");
}
...
}
But in my Controller this leads to an error message, that tells me I need to provide a logger as a parameter:
[GlobalException]
public class Inspection : Controller
{
...
I actually want the logger to be injected automatically by .NET Cores DI. How can I archive that?
I would not add the logging inside the exception filter attribute. I would let the exception handler do the logging. With that, I will still have a central place for the logging and any exception filters will throw exceptions. In a nutshell, I will achieve making my exception filters lightweight and separated the logging responsibilities. I don't have a code yet ready but will try to post something later.
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