c# - Log all handles exception
问题描述
How can I log all handled exceptions?
I want that whenever I catch an exception I should be able to log it
I want it to work globally and not that i should have to write it each time I catch
I tried subscribing to AppDomain.CurrentDomain.FirstChanceException
and it did work but I did not have the full stack trace and it called multiple times for each exception (I don't know why)
I also tried wrapping my controller with ActionFilterAttribute
like below and it worked on all exception from the controller only and not if the exception was caught in a service that was called from the controller
public class ExceptionLoggingHandler : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
if(filterContext.Exception !=null)
{
System.Diagnostics.Debug.WriteLine(filterContext.Exception.Message);
}
base.OnResultExecuted(filterContext);
}
}
解决方案
In ASP.NET MVC, you can add your filter as a global filter in the RegisterGlobalFilters
method inside FilterConfig.cs
. It should then catch all exceptions in all controller actions, and in any methods called from those actions - unless of course those methods already have catch blocks inside them which swallow the exception. In that case the caught exception (unless it's then re-thrown) will inevitably go undetected higher up the stack, which is, naturally, the whole point of catching exceptions.
e.g.
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new ExceptionLoggingHandler());
}
}
Also, your attribute should inherit from HandleErrorAttribute
, not ActionFilterAttribute
.
Something like this:
public class ExceptionLoggingHandler : HandleErrorAttribute
{
public ExceptionLoggingHandler() : base()
{
}
public override void OnException(ExceptionContext context)
{
System.Diagnostics.Debug.WriteLine(context.Exception.Message);
context.ExceptionHandled = true;
//.... continue to produce a suitable response
}
}
(In the .... area you can continue to develop the handler to log more sophisticated data, and return a suitable response, perhaps along the lines of this one (other examples are also available online.)
推荐阅读
- javascript - Array.concat() 返回一个空数组
- python-3.x - 为什么在 GridSearchCV 中使用 StandardScaler 时会得到不同的结果?
- python-3.x - 如何从类中的方法调用 __name__=='__main__'?
- python - 如何命名类变量
- spring-boot - 在 Spring RestTemplate 中注入 OpenTracing 的 SpanContext
- c# - FlurlClient 上链接的多个工厂方法
- c# - 错误 CS7036 没有给出与所需形式参数相对应的参数
- python - ValueError:使用 pd.apply() 时没有结果
- python - Botframework V4:Python Cosmos DB 配置
- python - 请求在 python beautifulsoup 中返回 403