Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ILogger in ExceptionFilter

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?

like image 310
David Avatar asked Sep 11 '25 13:09

David


1 Answers

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.

like image 175
alltej Avatar answered Sep 13 '25 07:09

alltej