Improved printf debugging on Rails
Posted by Kevin
Despite the power of formal debuggers, with their ability to peer into the depths of what is going on in your code, many of us still debug with what is sometimes called the “printf debugger”.
With the name coming from C, this practice of sprinkling printf (or moral equivalent) statements throughout your code can be used to form a picture of what’s going on behind the scenes. While this approach doesn’t have the flexibility or panache of using a formal debugger, it’s intuitive, fast, and in most cases good enough.
When I first started coding for Rails, I translated my printf debugging into puts debugging with little difficulty. Unfortunately, this often left me digging through hundreds of lines of server logs, most of which were not useful for the problem I was trying to solve. Luckily, Jimmy had also encountered this problem and while pair programming one day I saw his simple and elegant solution. Throughout his code he had putd statements, which instead of writing to stdout and getting lost in the server logs, wrote debug statements to a separate file.
Now instead of digging through server logs when I’m debugging, I just have a console open running tail -f tmp/debug.log showing me exactly what I want to see. This simple insight often speeds up my debugging by a factor of five or ten. The implementation cost of this timesaver? 9 lines of code:
if ['development', 'test'].include?(ENV['RAILS_ENV'])
DEVELOPMENT_DEBUG_LOG_FILE_NAME = "#{RAILS_ROOT}/tmp/debug.log"
DEVELOPMENT_DEBUG_LOGGER = Logger.new(DEVELOPMENT_DEBUG_LOG_FILE_NAME)
def putd(*args)
DEVELOPMENT_DEBUG_LOGGER.info(*args)
end
else
def putd(*args); end
end
It still amazes me how much this tiny function has improved my productivity. It makes me wonder how many other small workflow modifications with disproportionate returns there are out there to discover. Any readers with special tools or tricks of their own? What do you use?