Skip to content

Instantly share code, notes, and snippets.

@xanathar
Last active August 10, 2016 13:35
Show Gist options
  • Save xanathar/fdf8cb74340ae1e607cf92eebe565009 to your computer and use it in GitHub Desktop.
Save xanathar/fdf8cb74340ae1e607cf92eebe565009 to your computer and use it in GitHub Desktop.
ASP.NET MVC / WebApi Logger handler
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.ExceptionHandling;
using Castle.Core.Logging;
namespace XXXXXXXXXXXXXXXXXXXXXXXX
{
public class LoggerHandler : DelegatingHandler, IExceptionLogger
{
ILogger m_Logger;
public LoggerHandler(ILogger logger)
{
m_Logger = logger;
}
protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
string correlationid = LogRequestStart(request);
request.Properties.Add("__internal_correlation_id", correlationid);
var response = base.SendAsync(request, cancellationToken);
response.ContinueWith(resp =>
{
LogRequestComplete(correlationid);
});
return response;
}
private void LogRequestFailure(string correlation, Exception exception)
{
m_Logger.Warn($"{correlation} failed with exception : {exception}");
}
private void LogRequestComplete(string correlation)
{
m_Logger.Info($"{correlation} Completed.");
}
private string LogRequestStart(HttpRequestMessage request)
{
string correlation = $"{Guid.NewGuid().ToString("N")} - {request.Method.Method} {request.RequestUri.AbsoluteUri}";
m_Logger.Info($"{correlation} Started");
return correlation;
}
public Task LogAsync(ExceptionLoggerContext context, CancellationToken cancellationToken)
{
string correlationId = context.Request.Properties["__internal_correlation_id"] as string;
LogRequestFailure(correlationId, context.Exception);
return Task.FromResult(0);
}
}
}
@xanathar
Copy link
Author

Register with:

        var loggerHandler = this.container.Resolve<LoggerHandler>();
        config.Services.Add(typeof(IExceptionLogger), loggerHandler);
        config.MessageHandlers.Add(loggerHandler);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment