views:

108

answers:

1

So I use a lot of trace-code/logging when starting a new project, or debugging an existing one. I was wondering what techniques do you use to manage it, as I always end up deleting it before doing a commit, and then have to rewrite it if ever something else goes wrong.

I was thinking about having a development branch with all the trace-code, and the master would be clean, but it seems like it would be hard to sift through what is debugging code, and what should be merged.

Any suggestions?

+3  A: 

How about

def debug_only
  if $DEBUG
    yield
  end
end
...
debug_only { puts "Some tracing code." }

Passing -d on the command line will make $DEBUG true.

% ruby -e 'p $DEBUG'
false

% ruby -de  'p $DEBUG'
true

In that case, one possibility is to separate the tracing code from what you're tracing.

For eacample:

release.rb:

class A
  def stuff(a, b)
    # do stuff ...
  end
end

debug.rb:

require 'release'
class A
  alias release_stuff stuff
  def stuff(a, b)
    puts "calling stuff with (#{a.inspect}, #{b.inspect})"
    rv = release_stuff(a,b)
    puts "Done calling stuff."
    rv
  end
end

This has problems in that the granularity is a method, then again it may encourage you to write smaller methods. You can of course make it less verbose with some "metaprogramming".

You can also use instance_method,bind and define_method to make the copy of the old method anonymous.

And then you use it something like

ruby -d -rdebug program.rb
Logan Capaldo
actually I'm already using something very similar: `def verbose() $verbose = true; yield; ensure $verbose = false end` and I have a log() function which only outputs when $verbose is true. But my problem is with the actual trace-code, it's a real mess, and I just don't want it there in production code, I'd like my code to be free of any debug-specific fluff.
cloudhead
aha, hadn't thought of this—it might help!
cloudhead