Last active
August 10, 2016 13:35
-
-
Save xanathar/fdf8cb74340ae1e607cf92eebe565009 to your computer and use it in GitHub Desktop.
ASP.NET MVC / WebApi Logger handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Register with: