Is there a way to configure NLog to automatically log all exceptions my application can send? Currently I am going to all TRY/CATCH blocks and manually adding logging in the CATCH - but what if I miss some? And what if in the future someone else does

Is there a way to tell NLog to just always log all exceptions? Esspecially some that are not caught and could cause a popup?

2 Answers
2

As far as I know, there is no way to confineNLog to log all exceptions.

If all you want is to log unhandled exceptions, you could add an "UnhandledException Handler" to the AppDomain when initializing your application.
Note that under some circumstances it may not be possible to log the error (e.g. in case of an OutOfMemory exception or something terrible).

Note that the AppDomain also has a FirstChanceException event you can subscribe to, but this would mean that you get notified about every exception that occurs (and may be handled by the usercode) - in this are many.

Note that this will only allow you to log exceptions that cause your application to crash - you cannot prevent it to crash (therefore the name: unhandled exception).

Another option would be to use Aspect Oriented Programming (AOP) - and introduce a Logging aspect after each method call, in case of an error. If your application uses a Layered architecture, this may be relatively easy to do (e.g. add an aspect to all calls of your business logic layer...).

You may find a framework like PostSharp or Spring.Net useful (usually their websites provide some easy examples for that).

What is the scope of this AppDomain? Will it catch all unhandled exception in my project or only per class? Also I reference some DLLs what about exception from those? Do I need to add this code to each DLL (which are their own projects)?
– JSchwartzDec 15 '12 at 21:01

1

An Appdomain is a .net concept to define an isolated boundary for an application. If you create a Console application, it will be executed within one AppDomain. All required assemblies will be loaded in the same AppDomain too. If something happens within you application (no matter in what assembly) it will occur in the same appdomain. Usually you put the example code only once at the beginning of your application (e.g. in the Main method of your app, or in case of a WebApp in the global.asax in the application_start method). see msdn.microsoft.com/en-us/library/system.appdomain.aspx
– Bernhard KircherDec 15 '12 at 21:06