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

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • The explosion in mobile devices and applications has generated a great deal of interest in APIs. Today's businesses are under increased pressure to make it easy to build apps, supply tools to help developers work more quickly, and deploy operational analytics so they can track users, developers, application performance, and more. Apigee Edge provides comprehensive API delivery tools and both operational and business-level analytics in an integrated platform. It is available as on-premise software or through …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds