Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

ASP.NET Web API 2.1 includes a new global error handling capability. I found an example that demonstrates how to log exceptions into ELMAH. But I use NLog to log errors to a database table. Is it possible to use Web API global error handling with NLog? If so, please provide an example.

like image 208
demo Avatar asked Sep 16 '14 09:09

demo


People also ask

How does Web API handle exception globally?

Global Exception Filters With exception filters, you can customize how your Web API handles several exceptions by writing the exception filter class. Exception filters catch the unhandled exceptions in Web API. When an action method throws an unhandled exception, execution of the filter occurs.

How does Web API handle global exception in .NET core?

Use the UseExceptionHandler middleware in ASP.NET Core So, to implement the global exception handler, we can use the benefits of the ASP.NET Core build-in Middleware. A middleware is indicated as a software component inserted into the request processing pipeline which handles the requests and responses.


1 Answers

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.

like image 136
Filip W Avatar answered Sep 18 '22 23:09

Filip W