How to proper log every exception using OWIN

核能气质少年 提交于 2019-12-04 09:05:03

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/27216262/how-to-proper-log-every-exception-using-owin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!