DEV Community

Alex Antsiferov
Alex Antsiferov

Posted on

Tracing a method call in Ruby

Sometimes, we can't reproduce the issue in development and need to trace a method call in production console:

def trace
  trace = TracePoint.new(:call) do |tp| 
    p([tp.path, tp.lineno, tp.event, tp.method_id])
  end
  trace.enable
  yield
  trace.disable
end

trace { some_method(args) }
Enter fullscreen mode Exit fullscreen mode

In most cases, we want to see our own code only, so let's exclude libraries:

def trace
  trace = TracePoint.new(:call) do |tp|
    p([tp.path, tp.lineno, tp.event, tp.method_id]) unless /gems|ruby/.match?(tp.path)
  end
  trace.enable
  yield
  trace.disable
end
Enter fullscreen mode Exit fullscreen mode

There are other events to trace except :call, for example, :raise.

Top comments (0)