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.
Asked
Active
Viewed 2.2k times
2 Answers
54
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.
-
Would it be possible to somehow use the ExceptionLoggerContext (perhaps .ExceptionContext.ControllerContext.GetType()) to obtain a controller-specific logger? This would enable us to (via Nlog.config) turn on/off exception logging per controller. The logger above is instantiater using GetCurrentClassLogger which means that it won't be possible to differentiate between log event per controller right? – Emil G May 28 '15 at 07:04
-
this exception logging though, there is more to exception handling than just to log it. for example you want to return a uniform message back to the client with proper friendly error. is that covered by this pattern ? – Sonic Soul Jun 02 '15 at 18:36
-
@SonicSoul This requirement has nothing to do with a logger task. Just implement the IHttpActionResult interface and return a nice StringContent message. – Pascal Aug 02 '15 at 15:34
-
@EmilG Why do you log exceptions specific to controller? Just implement the ExceptionLogger class which acts globally (web api 2.2) – Pascal Aug 02 '15 at 15:35
-
1@Pascal: Controller specific exception logging is useful in my case because certain controllers are more important than others. Lets say I have AccountController and StatisticsController. Im that case, exceptions from AccountController are more important (and deserve specific exception handling) since such exception might mean that users cannot sign in, whereas exceptions occurring in StatisticsController is not so important. – Emil G Aug 13 '15 at 11:15
4
Other thing that might be handy WebApiContrib.Tracing.NLog package that allows you to use ITraceWriter interface to output to logs with NLog. A cool thing about ITraceWriter is that "all traces can correlate to the single request that caused that code to run (see this link)

oldbam
- 2,397
- 1
- 16
- 24