Reputation: 3657
I've implemented logging of all request/response packets in a message handler like this:
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);
}
It seems that about 10-20 api responses are not logged every day (out of multiple thousands). We have mobile devices that are calling these APIs and think its possible they make a request, then lose network connection, in which case the response is never sent or logged.
However, testing with postman, if we execute a log running request, then hit the cancel button in the middle of it, we do in fact see a response is eventually written to the log. It looks to be written when a subsequent request is made.
If Web API 2.0 gets a request, does it ALWAYS issue a response? Does it matter if the client aborted? Does it matter if the client lost connection to the network?
We are using log4net and a global exception logger to trap any errors. However, looking at all the logs around the time in which we "lose" a response, there is no exception logged. Here is the global logger:
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);
}
}
Here is how the handler and logger are registered at startup.
GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new GlobalExceptionLogger());
GlobalConfiguration.Configuration.MessageHandlers.Add(new MessageHandler());
I'm having a hard time testing this as well, any suggestions are much appreciated.
Upvotes: 0
Views: 228
Reputation: 1310
If you are running under OWIN, you can create middleware to do your logging of the request and the response independent of web api. If an exception occurs inside your web api application, the logging will still occur. Scott Allen has a good article on doing exactly this:
Simple Logging Middleware (Katana Part 4)
Upvotes: 0
Reputation: 417
All requests are being logged but some responses are not, true ? Try exception handling after request logging block, may be SendAsync method throws an exception before logging of response
Upvotes: 0