Log all unhandled exceptions in ASP.NET MVC
- log4net
- c#
- .NET
- asp.net-mvc
Create a new filter which implements IExceptionFilter and log however you’d like (I’m using log4net’s Logger class).
public class Log4NetExceptionFilter : IExceptionFilter
{
private static readonly ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public void OnException(ExceptionContext context)
{
Exception ex = context.Exception;
Logger.Error(ex.Message);
}
}
Register your filter globally in FilterConfig.cs.
public static class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new Log4NetExceptionFilter());
}
}
That’s literally it!