Alex's Blog

Alex's Blog

Tracing a method call in Ruby

#ruby#debugging

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) }

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

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


View original post and comments at dev.to →