Exception handling and logging strategy in .NET Exception handling and logging strategy in .NET asp.net asp.net

Exception handling and logging strategy in .NET


First, I would suggest reading the article "Vexing Exceptions" by Eric Lippert. This should give you some reasonable guidance on exception-handling (and more on exception throwing).

When it comes to exception logging, the easiest and cleanest approach is to have a "top-level" exception handler responsible for dealing with all otherwise unhandled exceptions and record them to a log for analysis. This can be done in ASP.NET applications through the HttpApplication.Error event which you can hook into through your Global.asax file.

If a part of the application is trapping an error (catching it) and handling it in some way, it may be appropriate to log a warning or informational at that point, so can record a problem occurred, but that the system dealt with it. Try to avoid filling your code with these though, as they can quickly become a maintenance problem.


In my MVC3 application I use ELMAH for the exception handling as described here How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?, while if I need to log a custom message I use the Trace methods that comes from the System.Diagnostics, here a useful link Overriding System.Diagnostics.Trace.WriteLine to log to a file.

UPDATE Now you can set up elmah in your application directly with the NuGet packager. http://gregorsuttie.wordpress.com/2011/02/02/elmah-using-nuget-what-they-are-and-why-you-should-use-them-part-1/


Take a look at Enterprise Library. It will provide you with a very flexible logging tool and other goods I think you'll enjoy. For example: you can use the Police Injection Application Block (taht implements AOP) to catch all exceptions in your code without writing a line of code.