Additional Debugging Techniques in C#

Mike Borromeo's "Debugging Techniques in C#" presented a useful Debug class that can log debug or trace messages with caller and code location information automatically. (See: http://www.codeguru.com/net_general/Debugging.html) It was a great idea and it helped my project tremendously.

There is one assumption made by the Debug class that was presented that is not always true. The Debug class assumes that it lives in the same assembly as the code that uses it. When a call from another assembly calls in, it would raise an exception. An exception from the debug harness code itself is probably the last thing programmers want to see when debugging. I've modified the code presented by Mike's to make it more friendly to other assemblies. I've also made some modifications that fit my own needs. These modifications may be useful to you as well. Here are the details:

1.  An exception is raised in Mike's code when a call from another assembly comes in. This is because namespaces are added to the Hashtable by getting all namespaces in the assembly that the Debug class lives in.
Assembly a = Assembly.GetAssembly( new Debug().GetType() );
foreach( Type type in a.GetTypes() )
{
   if( ! namespaces.Contains( type.Namespace ) )
       namespaces.Add( type.Namespace, true );
}

When a caller from another assembly wants to log a message, "namespaces[sf.GetMethod().DeclaringType.Namespace]" would get a "null". This would cause the namespace checking statement in the Log() method to throw an exception because one cannot convert "null" to a "bool".

if( (bool) namespaces[ sf.GetMethod().DeclaringType.Namespace ] )
       OnLog( msg, 
              sf.GetFileName(), 
              sf.GetFileLineNumber(),
              sf.GetMethod().ToString() );

To solve this, I added code in Log() to check if the namespace is in the Hashtable. If not, the new namespace would be added. Now one can compile the Debug class as a separate assembly, install it in the GAC and share it across all projects.

2.  Mike's log message prints out the full path of the caller file regardless of the length of the path. It a piece of source code is in a deep subdirectory, the long path would make the real message less easy to read. I improved this by printing at most two directory names on the path, namely the topmost and the bottommost ones.

private static string FormatMsg(string msg,
                                string file,
                                int lineNumber,
                                string methodName,
                                string method)
{
   string str;
   string part1 = "[" + msg + "] " + methodName + "()" + ":";
   char[] delimiters = {'\\'};
   string [] elements = file.Split(delimiters);

   if (elements.Length<=5)
      str = part1 + file + ":" + lineNumber + " " + method;
   else
    str = part1 + elements[0] + "/" + 
          elements[1] + "/.../" + 
          elements[elements.Length-2] + "/" + 
          elements[elements.Length-1] +
          ":" + lineNumber + " " + method +
          " [" + file + "]";

   return str;
}

So instead of printing a message like:

[ERROR c:\Document and Settings\Somebody\work\programming\
VisualStudio.NET\csharp\samples\debugging\debugconsole.cs:
157 Void .ctor()]:This is a test debug error statement 

the message is cut to:

[ERROR: c:\Document and Settings\...\debugging\
debugconsole.cs:157 Void .ctor()]: This is a test debug 
error statement

This had worked better for me. Of course, the choice of preferrable message format is higly personally. It doesn't hurt to have one more choice.

Note that I did not use the DebugConsole. I felt the standard output window in IDE is sufficient. For those using the DebugConsole, some code needs to be added to show the added namespaces on the DebugConsole window.

Downloads

Download source - 2 Kb


Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

  • In support of their business continuity and disaster recovery plans, many midsized companies endeavor to avoid putting all their eggs in one basket. Understanding the critical role of last-mile connectivity and always available Internet access for their enterprises, savvy firms utilize redundant connections from multiple service providers. Despite the good intentions, their Internet connectivity risk may still be in a single basket. That is because internet service providers (ISPs) and competitive local …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds