I'm testing out an MVC 6 Web Api and wanted to implement logging into a global error handler. Just guaranteeing no errors get out of the system without being logged. I created an ExceptionFilterAttribute and added it globally in the startup:
public class AppExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
//Notice pulling from HttpContext Application Svcs -- don't like that
var loggerFactory = (ILoggerFactory)context.HttpContext.ApplicationServices.GetService(typeof (ILoggerFactory));
var logger = loggerFactory.Create("MyWeb.Web.Api");
logger.WriteError(2, "Error Occurred", context.Exception);
context.Result = new JsonResult(
new
{
context.Exception.Message,
context.Exception.StackTrace
});
}
}
Now in the startup, I'm adding this filter in:
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new AppExceptionFilterAttribute());
});
This all seems kind of brute force...is there a better way to get here using MVC 6?
Things I don't like or am unsure about with this approach:
- Don't like pulling DI from http context
- Don't have much context about the controller that originated the error (perhaps I can get it from the context in some way).
The other option I can think of is having a base controller that accepts an ILoggerFactory that all controllers inherit from.
Was wondering if there was some kind of diagnostics middleware that would allow logging to be inserted...