Web Api -异常不记录日志
本文关键字:记录日志 异常 Api Web | 更新日期: 2023-09-27 18:02:57
我有以下类
public class WebApiExceptionLoggingFilter : ExceptionFilterAttribute
{
private readonly ILog _logger;
public WebApiExceptionLoggingFilter(ILog logger)
{
this._logger = logger;
}
public override void OnException(HttpActionExecutedContext filterContext)
{
//Logging Exception
_logger.Error("An unhandled exception was thrown", filterContext.Exception);
//Changing exception message to something generic.
var exceptionMessage = "An error occurred and logged during processing of this application.";
//Throwing a proper message for the client side
var message = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(exceptionMessage),
ReasonPhrase = exceptionMessage
};
throw new HttpResponseException(message);
}
}
我将它注册为:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Filters.Add(new WebApiExceptionLoggingFilter(LogManager.GetLogger("Web Api Unhandled Exception Logger")));
}
我有另一个过滤器属性注册为我的mvc控制器,它是注册在FilterConfig.cs文件。当控制器动作中发生异常时,将通过log4net记录到windows事件查看器。当在调用web api控制器动作时发生异常时,上面处理程序中的OnException方法被击中并调用_logger.log,但没有任何内容被记录到事件查看器中。我错过什么了吗?
最后我发现了问题。
我有这个在我的assemblyinfo.cs
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
我需要这个
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config",Watch = true)]