Hi,
Don't underestimate the power of instrumentation! (cheesy, I know)
Seriously, let's say you use everyone's suggestions to get the exception
logged, which is a great idea to begin with. Now, how do you debug it?
Sure, you may have the call stack and the exception but you'll probably have
no idea about the application's *state* at the time of the crash. With
tracing to the Application event log you will.
Just add calls to Trace.WriteLine in places where the state of the
application changes frequently and supply a short message and the values of
some of the local variables and fields. You can do the same in your
exception handling code as well, which should be used sparingly in most
applications.
Before the application starts (a good place is the Main method of your
program, before the call to Application.Run), add a call to:
System.Diagnostics.Trace.Listeners.Add(
new System.Diagnostics.EventLogTraceListener(Application.ProductName));
All of your trace output will be logged to the Application event log with
your app's name as the event source.
If you use a global TraceSwitch in your application then you can easily turn
on/off tracing (and, therefore, the event log output) using the app.config
file. If a user reports crashes or strange behavior you can ask them to
turn on tracing for you and send you the event log if the error occurs
again.
// assuming traceSwitch is an instance of the TraceSwitch class:
if (traceSwitch.TraceVerbose)
Trace.TraceInformation("Updated stock from {0} to {1}", stockOld,
stockNew);
TraceSwitch Class
http://msdn2.microsoft.com/en-us/library/system.diagnostics.traceswitch.aspx
I like to use the Program class created by VS 2005 to encapsulate a global
switch:
public static class Program
{
private static readonly TraceSwitch traceSwitch =
new TraceSwitch("Global",
Application.ProductName + " Trace Switch");
[Conditional("TRACE")]
public static void TraceVerbose(string format, params object[] args)
{
if (traceSwitch.TraceVerbose)
Trace.TraceInformation(format, args);
}
[Conditional("TRACE")]
public static void TraceVerbose(string message)
{
if (traceSwitch.TraceVerbose)
Trace.TraceInformation(message);
}
}
You can then use something like the following throughout your code:
Program.TraceVerbose("Updated stock from {0} to {1}", stockOld, stockNew);