RubyGuides
Share this post!

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 %8sn", 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:

ruby tracing

1 comment
megas says 6 years ago

Good topic, thanks

Comments are closed