我已经在这样的消息处理程序中实现了所有请求/响应数据包的日志记录:
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var correlationId = Guid.NewGuid();
RequestApiLogger.LogHttpRequest(request, correlationId);
return await base.SendAsync(request, cancellationToken).ContinueWith(
task =>
{
var response = task.Result;
response.Headers.Add("http-tracking-id", correlationId.ToString("D"));
ResponseApiLogger.LogHttpResponse(response, correlationId);
return response;
}, cancellationToken);
}
似乎每天没有记录大约 10-20 个 api 响应(数千个)。我们有正在调用这些 API 的移动设备,并认为它们可能会发出请求,然后失去网络连接,在这种情况下,永远不会发送或记录响应。
但是,用 postman 测试,如果我们执行一个日志运行请求,然后在它中间点击取消按钮,我们确实看到最终将响应写入日志。它看起来是在发出后续请求时写入的。
如果 Web API 2.0 收到请求,它是否总是发出响应?客户中止是否重要?如果客户端失去与网络的连接,这有关系吗?
我们使用 log4net 和全局异常记录器来捕获任何错误。但是,查看我们“丢失”响应时的所有日志,没有记录异常。这是全局记录器:
internal class GlobalExceptionLogger : ExceptionLogger
{
private static readonly ILog Log4Net = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public override void Log(ExceptionLoggerContext context)
{
Log4Net.Error(
string.Format("Unhandled exception thrown in {0} for request {1}", context.Request.Method,
context.Request.RequestUri), context.Exception);
}
}
这是处理程序和记录器在启动时注册的方式。
GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new GlobalExceptionLogger());
GlobalConfiguration.Configuration.MessageHandlers.Add(new MessageHandler());
我也很难对此进行测试,非常感谢任何建议。