Skip to content

Instantly share code, notes, and snippets.

@xakpc
Last active August 1, 2017 22:04
Show Gist options
  • Save xakpc/0eb40d212f9ca108fa3e85e143e12ae6 to your computer and use it in GitHub Desktop.
Save xakpc/0eb40d212f9ca108fa3e85e143e12ae6 to your computer and use it in GitHub Desktop.
ASP.NET WebAPI requests logger by MessageHandler
using System.Diagnostics;
using System.Web;
using Hangfire;
using Hangfire.SimpleInjector;
using GlobalConfiguration = System.Web.Http.GlobalConfiguration;
namespace NameSpace
{
public class WebApiApplication : HttpApplication
{
protected void Application_Start()
{
Trace.TraceInformation("Application_Start");
///...
GlobalConfiguration.Configuration.MessageHandlers.Add(new MessageLoggingHandler());
}
}
}
using System;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace NameSpace
{
public abstract class MessageHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var corrId = $"{DateTime.Now.Ticks}{Thread.CurrentThread.ManagedThreadId}";
var requestMessage = await request.Content.ReadAsByteArrayAsync();
await IncommingMessageAsync(corrId, request.Method, request.RequestUri, requestMessage);
var response = await base.SendAsync(request, cancellationToken);
byte[] responseMessage;
if (response.IsSuccessStatusCode)
responseMessage = response.Content != null
? await response.Content.ReadAsByteArrayAsync()
: Encoding.UTF8.GetBytes("null");
else
responseMessage = Encoding.UTF8.GetBytes(response.ReasonPhrase);
await OutgoingMessageAsync(corrId, request.Method, request.RequestUri, responseMessage);
return response;
}
protected abstract Task IncomingMessageAsync(string correlationId, HttpMethod method, Uri uri, byte[] message);
protected abstract Task OutgoingMessageAsync(string correlationId, HttpMethod method, Uri uri, byte[] message);
}
}
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using NLog;
namespace NameSpace
{
public class MessageLoggingHandler : MessageHandler
{
private static Logger _logger = LogManager.GetLogger("WebApiLogger");
protected override Task IncomingMessageAsync(string correlationId, HttpMethod method, Uri uri, byte[] message)
{
return Task.Run(() =>
{
var log = $"{correlationId} - Request - Method:{method} Uri:'{uri}' Message:{Encoding.UTF8.GetString(message)}";
_logger.Trace(log);
Debug.WriteLine(log);
});
}
protected override Task OutgoingMessageAsync(string correlationId, HttpMethod method, Uri uri, byte[] message)
{
return Task.Run(() =>
{
var log = $"{correlationId} - Response - Method:{method} Uri:'{uri}' Message:{Encoding.UTF8.GetString(message)}";
_logger.Trace(log);
Debug.WriteLine(log);
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment