1

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?

svick
  • 214,528
  • 47
  • 357
  • 477
David
  • 1,115
  • 2
  • 11
  • 26
  • could you post the specific error message –  Sep 12 '16 at 11:02
  • You need to use ServiceFilter attribute. Possible duplicate of [ASP.Net Core (MVC 6) - Inject service into Action Filter](http://stackoverflow.com/questions/36109052/asp-net-core-mvc-6-inject-service-into-action-filter). – Set Sep 12 '16 at 12:49

1 Answers1

2

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.

alltej
  • 5,306
  • 4
  • 34
  • 65