Global exception handling in ASP.NET Web API 2.1 with NLog?

It’s actually quite simple, you either implement IExceptionLogger by hand or inherit from the base class, ExceptionLogger.

public class NLogExceptionLogger : ExceptionLogger
{
    private static readonly Logger Nlog = LogManager.GetCurrentClassLogger();
    public override void Log(ExceptionLoggerContext context)
    {
        Nlog.LogException(LogLevel.Error, RequestToString(context.Request), context.Exception);
    }

    private static string RequestToString(HttpRequestMessage request)
    {
        var message = new StringBuilder();
        if (request.Method != null)
            message.Append(request.Method);

        if (request.RequestUri != null)
            message.Append(" ").Append(request.RequestUri);

        return message.ToString();
    }
}

Also add it to the config:

var config = new HttpConfiguration(); 

config.Services.Add(typeof(IExceptionLogger), new NLogExceptionLogger()); 

You can find full sample solution here.

Leave a Comment