【问题标题】:Web Api - Exception not loggingWeb Api - 异常未记录
【发布时间】:2015-07-15 17:43: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,但不会将任何内容记录到事件查看器中。我错过了什么吗?

【问题讨论】:

    标签: c# exception log4net asp.net-web-api


    【解决方案1】:

    我最终找到了问题。

    我的 assemblyinfo.cs 中有这个

    [assembly: log4net.Config.XmlConfigurator(Watch = true)] 
    

    我需要这个

    [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config",Watch = true)] 
    

    【讨论】:

      猜你喜欢
      • 2015-06-16
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      • 2015-04-15
      • 2019-08-30
      • 1970-01-01
      相关资源
      最近更新 更多