In Web API 2.1 is new ​​Global Error Handling​​.

I found some example how to log exceptions into Elmah ( ​​elmah sample​​ ).

But I use NLog to log errors into database table.

Is it posible to use Web API Global Error Handling with NLog?

Please provide some example.

 

 

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​​.