Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log all exceptions in .NET app using log4net

Tags:

.net

log4net

Is there any easy way to auto write all the unhandled exception in my application to a log file? I`m using log4net as my logging solution.

My application hosted as a windows service.

Thanks.

like image 635
Avi K. Avatar asked Sep 20 '10 07:09

Avi K.


1 Answers

It depends on the type of application you are running. You should always register the AppDomain.UnhandledException event during startup of your application:

AppDomain.CurrentDomain.UnhandledException += (s, e) =>
{
    var exception = (Exception)e.ExceptionObject;
    // Log to log4net.
};

When using a ASP.NET application, you can hook onto the HttpApplication.Error event use the Global.asax to do this. When using a Windows Forms application you can hook onto the Application.ThreadException event.

like image 159
Steven Avatar answered Oct 24 '22 21:10

Steven