[转]Global exception handling in Web API 2.1 and NLog

本文转自:https://stackoverflow.com/questions/25865610/global-exception-handling-in-web-api-2-1-and-nlog

 

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.

 

posted on 2017-12-20 10:33 freeliver54 阅读(...) 评论(...) 编辑 收藏

导航

公告