Use*_*rol 7 .net error-handling logging asp.net-web-api asp.net-web-api2
[IExceptionLogger][1]当从控制器操作抛出异常时,我的异常记录器实现被调用两次.
context.RequestContext.Configuration.Services.GetServices(typeof(IExceptionLogger))
Run Code Online (Sandbox Code Playgroud)
这会返回一个条目,所以我确定只注册了一个记录器实例.我不希望我的未处理异常被记录两次,我不认为这是预期的默认行为.我如何解决导致它的原因?
如果我在LogAsync()方法中设置断点,则callstack会[External Code]在两个调用中显示.
[RoutePrefix("test")]
public class MyController : ApiController
{
[HttpGet, AllowAnonymous]
[Route("test")]
public string GetTest()
{
throw new InvalidOperationException("Shit happens");
}
}
Run Code Online (Sandbox Code Playgroud)
记录器注入如下:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
尝试更改WebApiExceptionLogger,以便它继承自ExceptionLogger.ExceptionLogger实现了一个名为"ShouldLog"的自定义方法,该方法可以抑制重复调用.(除非可以提供类似的逻辑,否则不应覆盖此方法).这解决了我的问题.
我认为这种行为是因为当管道中的不同位置发生异常时,WebApi2会为每个请求调用两次Log/LogAsync.除非你有逻辑来处理这个问题,否则你最终会遇到重复的日志调用.
| 归档时间: |
|
| 查看次数: |
1020 次 |
| 最近记录: |