log4net 捕获 Web API 的所有控制器操作错误

本文关键字:控制器 操作 错误 捕获 Web API log4net | 更新日期: 2023-09-27 18:36:11

我目前正在实现log4net来捕获Web api控制器的异常。

我想知道如何捕获控制器内任何操作中的所有错误?

我不想理想地完成每个动作并添加尝试捕获,如果可以帮助它?

log4net 捕获 Web API 的所有控制器操作错误

您需要注册一个 IExceptionLogger

e.x.: GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new YourWebApiExceptionLogger());

您可以实现 System.Web.Http.Filters.ActionFilterAttribute。在 OnActionExecute 中,您可以处理日志记录:

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
            if (actionExecutedContext.Response != null)
            {
              //ok
            }
            else
            {
                _logger.ErrorFormat("actionExecutedContext.Response == null will result in 500, unhandled exception"); //Add extra information here
            }
    }

然后,可以将此操作筛选器作为属性添加到要记录的方法中。