当从控制器操作抛出异常时,我的实现[IExceptionLogger][1]的异常记录器被调用两次。
context.RequestContext.Configuration.Services.GetServices(typeof(IExceptionLogger))这将返回单个条目,因此我确信只注册了记录器的一个实例。我不希望未处理的异常被记录两次,我不认为这是预期的默认行为。我该如何排查故障原因?
如果我在LogAsync()方法中设置了断点,那么调用栈在两个调用中都会显示[External Code]。
[RoutePrefix("test")]
public class MyController : ApiController
{
[HttpGet, AllowAnonymous]
[Route("test")]
public string GetTest()
{
throw new InvalidOperationException("Shit happens");
}
}记录器是这样注入的:
config.Services.Add(typeof(IExceptionLogger), new WebApiExceptionLogger());
public class WebApiExceptionLogger : IExceptionLogger
{
private readonly ILoggingService loggingService;
public WebApiExceptionLogger()
{
this.loggingService = ServiceContainer.Factory.Resolve<ILoggingService>();
}
public Task LogAsync(ExceptionLoggerContext context, CancellationToken cancellationToken)
{
this.loggingService.Log(LogLevel.Error, this.GetType().Name, context.Exception, "Ship has just happened");
return Task.FromResult(true);
}
}发布于 2017-02-01 16:37:55
尝试更改WebApiExceptionLogger,使其改为从ExceptionLogger继承。ExceptionLogger实现了一个名为"ShouldLog“的自定义方法,用于抑制重复调用。(您不应该覆盖此方法,除非您可以提供类似的逻辑)。这为我解决了这个问题。
我认为这是因为当管道中的不同位置发生异常时,WebApi2会为每个请求调用两次日志/日志异步。除非您有处理此问题的逻辑,否则最终会出现重复的日志调用。
发布于 2017-07-20 17:49:10
关于何时使用autofac解决全局异常处理程序的问题,请注意,您可以这样做:
1)确保先调用autofac类型注册方法。在这种情况下,您通常会执行以下操作:
builder.RegisterType<AppExceptionLogger>().AsSelf().AsImplementedInterfaces();
builder.RegisterType<AppExceptionHandler>().AsSelf().AsImplementedInterfaces();2)将以下内容添加到您的WebApiConfig.Register(HttpConfiguration配置)或类似的呼叫中:
// Inject our exception logger and handler (get one from DR/Autofac)
config.Services.Replace(typeof(IExceptionHandler), config.DependencyResolver.GetService(typeof(AppExceptionHandler)));
config.Services.Replace(typeof(IExceptionLogger), config.DependencyResolver.GetService(typeof(AppExceptionLogger)));这在没有OWIN的情况下可以工作,但在那里也应该很好。
https://stackoverflow.com/questions/41870954
复制相似问题