Ruby tracing – A useful debugging tool

Tracing is following all the steps taken by a program, specially function calls/methods, this can be a useful debugging tool when tracking down some problems with your application.

In Ruby we have a tracing tool built-in, we can invoke it with ruby -rtracer script.rb but as you can see here it’s not easy to tell what’s going on:

#0:test.rb:2::-: def another_call
#0:test.rb:7::-: def more_depth
#0:test.rb:12::-: def trace_testing(*argv)
#0:test.rb:17::-: 3.times do |t|
#0:test.rb:18::-: puts trace_testing('abcd',12345 * t, [1,2,3],:test => 'A')
#0:test.rb:12:Object:>: def trace_testing(*argv)

What we can do is implement our own tracer and format the output to our liking, for this Ruby provides us with the set_trace_func method, we setup our tracing by giving this method a proc that will be called for each tracing event.

set_trace_func proc { |event, file, line, id, binding, classname|
printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname

Here is a summary of what each argument means:

event, this is whats happening in this step of execution, it can be one of the following:
“c-return”, “end”, “return”, “c-call”, “line”, “call”, “class”
file, this is the file where the event happens
line, the line number
id, this is the method name we are in
binding, the current scope where we are running
classname, this one doesn’t need much explanation :)

I have made a gem that implements this and focuses on ruby method calls:

gem install simple-tracer

You can call it with just “st my_script.rb” and this is how it looks:

About these ads

, , , ,

  1. #1 by megas on June 19, 2012 - 8:48 pm

    Good topic, thanks

  1. Ruby NoName Podcast S04E11 | | CopyBase.RU - Интересное из сетиCopyBase.RU — Интересное из сети

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

%d bloggers like this: