12

With ELMAH feature in web api 2.0 and Centralized logging and error handling , runtime calls logging module and decide if it can be handled then calls the handler else just logs it.. how can this feature be added in web api core. as we don't have inbuilt centralized unhandled logging feature..

One way I got is to use ExceptionHandler middleware and when it gets called, get the exception and log it or send email.. but what if handler doesn't get called .. how to log those unhandled exceptions ?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
zubin joshi
  • 187
  • 1
  • 1
  • 7

3 Answers3

14

Middleware could be a way to go yes. I've written a guide here: Error Logging Middleware in ASP.NET Core.

I would probably look at Microsoft.Extensions.Logging in combination with a logging framework like Serilog, NLog or log4net.

ThomasArdal
  • 4,999
  • 4
  • 33
  • 73
  • Thanks Thomas, does it depend the order of registrations of Error logging and handling middleware ? – zubin joshi Dec 07 '17 at 21:26
  • 1
    If adding error logging middleware, you should add it after other pieces of middleware dealing with exceptions. You want your middleware to run as close to the thrown exception as possible, since other middleware may "swallow" exceptions. – ThomasArdal Dec 07 '17 at 21:29
  • "While calling the UseMiddleware<> method in Startup.cs definitely work, it is considered good practice to create a custom Use-method:" - ...why is that? I can't stand when devs throw out "it's best practice to..." without any justification. Why is it "best practuce" to introduce a useless wrapper method? I'm fine being proven wrong here, I'm just not seeing it. That said, the article is useful. – Ed S. Dec 10 '20 at 18:36
  • Good point Will make sure to update the post. – ThomasArdal Dec 10 '20 at 18:37
0

Try this port of Elmah to .NET Core.

services.AddElmah(); // in ConfigureServices 

app.UseElmah(); // in Configure, before UseMvc()
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Andy
  • 11
  • Just a quick question, Do I have to manually put try catch blocks everywhere and log exceptions to Elmahcore using `HttpContext.RiseError()`? or I would automatically catch thrown exceptions from my code once its configured? – Hamza Khanzada Jan 29 '20 at 10:25
0

If you're already using Application Insights, you can set up alerts in the portal. https://learn.microsoft.com/en-us/azure/azure-monitor/learn/tutorial-alert

Kyle J V
  • 563
  • 5
  • 21