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:

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.

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:

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

Leave a Reply