Version 2 of Debugging Aid For Production Code

Updated 2002-09-05 21:05:44

This is a bit of code we use to manage inline debugging code. We use a global variable "::DEBUG" to set the debugging state, when ::DEBUG < 0, the code runs "flat out" regardless of the arguments sent to debugPuts.

The procedure addLogEntry is not provided here. It is a very elaborate set of procs which provide custom trace information for our system -- replace it with your own handler.

 ## ******************************************************** 
 ##
 ## Name: debugPuts
 ##
 ## Description:
 ## Used to make optional puts's and addLogEntry's based on
 ## debugging level. setting ::DEBUG > 1 turns on putsing to
 ## stderr.
 ## An optional special handler may be specified as a third
 ## command line argument.
 ##
 ## Parameters:
 ## msg     - text to be displayed/logged
 ## level   - optional level modifier
 ## handler - optional special handler 
 ##           (not the default addLogEntry)
 ## Usage:
 ##
 ## Comments:
 ## Convenience routine for making debugging switchable.
 ## returns in 25 microseconds if ::DEBUG < 0.
 ## If ::DEBUG < 0 then the debug level cannot be
 ## used to cause debugging output.

 proc debugPuts { { msg "" } { level 0 } { handler "" } } {
     if { $::DEBUG < 0 } { return {} }
     ;## get global debug level if none is provided
     if { ! $level } { set level $::DEBUG }
     ;## if debugging is on...
     if { $level } {
        if { [ regexp {^$} $handler ] } {
           set handler "addLogEntry"
           }
        if { [ string length $msg ] } {
           if { [ catch { uplevel $handler [ list $msg ] } err ] } {
              addLogEntry "debugPuts:$handler: $err (message was: $msg)"
              }
           if { $level > 1 } {
              puts stderr $msg
              }
           }
        }   
     return {}
 }
 ## ******************************************************** 
 ;## PSE

CLL - I would suggest the following to keep the production code as fast as possible..

if {$::DEBUG < 0} {

  proc debugPuts {{msg {}} {level 0} {handler {}}} {
    # body of the above proc
  }

} else {

  proc debugPuts {{msg {}} {level 0} {handler {}}} {return}

}

In the original example, every single call to debugPuts (even when debugging is totally off) requires a conditional check. This can slow things down tremendously. With this second example there are ZERO conditional checks when debugging is turned off. It does lack the advantage of enabling easy run-time debug mode switching. However, that could be easily taken care of by putting all of the above code into a single proc, calling it once to initialize, and then calling it thereafter whenever debugging state changes.


Oh, you might want to have a look on Errx, too. -Martin