Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to proper log every exception using OWIN

my question should be quite simple, but unfortunately I had no luck in solving it.

Basically, I have some Web API controllers hosted by OWIN and deployed on Azure.

I really need to track down exceptions that occur in each middleware (for example OAuthAuthorizationServerProvider or SignalR Persistent Connections), but I definitely don't have a clue on how to achieve it.

  • I tried Elmah, but it doesn't seem to work properly with OWIN due to lacking HttpContext.
  • I tried using log4net, but I'm only able to log exceptions thrown by Web API Controllers using a custom ExceptionFilterAttribute.. others are ignored.
  • I tried to define a custom LoggerFactory and to assign it in Startup, using app.SetLoggerFactory(new MyLoggerFactory()), but exception thrown by other middlewares are not logged.
  • I tried to get at least a meaningful error message sent to the client, but despite <customErrors mode="Off"/> and <deployment retail="false"/>, Azure refuses to return anything but {"message":"an error has occurred"}.. I tried both Azure Web Sites and Azure Cloud Services.
  • I saw some cloud alternatives that should work with OWIN, like Elmah.io or Raygun.io, but I don't need their cloud features and it is definitely not worth paying hundreds $ per year just to log some exceptions.

What should be the best way to log any possible exception thrown by my application?

Thanks for your help

like image 333
Menion Leah Avatar asked Nov 30 '14 17:11

Menion Leah


1 Answers

have you take a look at this link ? http://www.asp.net/web-api/overview/error-handling/web-api-global-error-handling

Because you can't catch all the exceptions using an exceptionFilter, they propose to use a IExceptionLogger and IExceptionHandler to allow global error handling in Web Api 2.

After that, if it's not fit your need, you can construct an OwinMiddleWare that you will place in first position (before the Authenticate stage), this middleware could :

  1. create a requestId in the header of the response
  2. analyse the response code, before sending response, and if it's not a IsSuccessStatusCode, you could log the exception message to a DB and replace the content of the response to send a simple error message to the client using the requestId (to allow you to find the related exception in your db)

hope this help

like image 73
Jeremie Devillard Avatar answered Nov 19 '22 01:11

Jeremie Devillard