I have a WinForms application and I need to log all exceptions (to a file, to a webservice, whatever), either handle开发者_Go百科d and unhandled. How can I do this?
The most commonly used logging framework in the .NET world is log4net.
There are two steps that are required to integrate log4net in your application:
- Configure log4.net. For example, check out FileAppender on log4net Config Examples page.
- Prepare your classes to use log4net:
Each class should contain a field used for logging:
private static ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Now, whenever you'll have to handle an exception, you would do the following:
try
{
// Do stuff here
}
catch (Exception ex)
{
_logger.Error("Operation failed.", ex);
}
In this way you've solved only half of the problem: handled exceptions.
In order to catch all unhandled exceptions in a Windows Forms application, you'll have to handle 2 events provided by .NET framework:
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.ThreadException += Application_ThreadException;
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
_logger.Error("Unhandled exception.", (Exception)e.ExceptionObject);
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
_logger.Error("Unhandled application exception.", e.Exception);
}
That's all.Nice and easy!
Things get complicated when you start to deliver your application to one or more customers. This is because you need to ask your customers to provide you the log files in order to check whether the application encountered any issue.
Therefore, you have to solve two problems:
- How to get notified when something wrong happens in your application?
- How to get detailed information about the exception, environment, etc. ?
A solution to both problems would be to use a dedicated service that centralizes all your exceptions in one single place and that notifies you whenever your application encounters any exception.
There are several services that try to solve all the these problems, one of them being ExceptionTail.
A very nice feature of ExceptionTail is its seamless integration with existing applications that use log4.net via a custom log4net appender.
This means that you don't have to recompile your entire application in order to use the service. Just drop some dlls in your application's folder, add something to the application configuration file, and you're good to go.
I haven't used it, but Exceptioneer is highly regarded...
精彩评论