Tracing method execution

December 11th, 2006

Update: tweaked the Proc to trace returns by default as well, and tell you what kind of call happened. Also tweaked the order of fields.

Just a quick little snippet to make up for my extended absence. This is probably old news to a lot of readers, but someone should get some value out of this.

Sometimes, you need to trace execution through your script. In my case, I’m debugging some tweaks to ActiveRecord::Migration and something is getting hosed along the way. Kernel#set_trace_func to the rescue!

Drop the following in your .irbrc, fire up irb, call enable_trace, and then whatever you’re trying to do:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

def enable_trace( event_regex = /^(call|return)/, class_regex = /IRB|Wirble|RubyLex|RubyToken/ )
  puts "Enabling method tracing with event regex #{event_regex.inspect} and class exclusion regex #{class_regex.inspect}"

  set_trace_func Proc.new{|event, file, line, id, binding, classname|
    printf "[%8s] %30s %30s (%s:%-2d)\n", event, id, classname, file, line if
      event          =~ event_regex and
      classname.to_s !~ class_regex
  }
  return
end

def disable_trace
  puts "Disabling method tracing"

  set_trace_func nil
end

For bonus points, you can pass in alternate regexes depending on what you want to capture. Out of the box, it’ll only show you Ruby method calls, and will exclude anything that comes from a class matched by the class_regex parameter. Check out


ri Kernel#set_trace_func

for more details about what you can get/do.

1 Response to “Tracing method execution”

  1. Chad Humphries Says:

    Sweet! Just what I was looking for.

Sorry, comments are closed for this article.