TracePoint API – what is it?

TracePoint API – what is it?
Average rating: 0
(0 votes)

Thanks! You’ve rated this material!

Sometimes you need to trace all invoked methods in your program. Earlier there was a set_trace_func tool that was very slow and not convenient. Fortunately, starting from Ruby 2.0 we have another one – TracePoint API which aims to replace it. Strictly speaking, the TracePoint API is simply an Object-Oriented wrapper around the now obsolete Kernel#set_trace_func.

Please have a look at small example. I’ve got idea of usage here and modify it for my needs.
So, we’ll create a simple middleware in our Rails App:


# lib/trace_point.rb
class TracePoint
  class Middleware

    def initialize(app)
      @app = app

    def call(env)
      stats = []
      trace = do |tp|
        if /app//.match(tp.path)
          stats << "#{tp.path}  ->  #{tp.defined_class} # #{tp.method_id}"
      response =
      puts "Start of #{env}"
      stats.uniq.each {|elem| puts elem.slice(elem.index("/app/")..-1)}
      puts "End of #{env}"



… one line goes to our config/application.rb


# config/application.rb
require_relative '../lib/trace_point'
config.middleware.insert_before(ActionDispatch::Static, TracePoint::Middleware)

And — voilà — you’ve got a detailed list of all invoked classes and methods of your Rails App in order they were called. You can modify code for your purpose to get more clean trace for your needs.
Where to use it – it’s up to you. E.g. it can help you to conquer the world make a detailed list of methods for test coverage or will be useful during debugging.

Rate this article, if you like it

Thanks! You’ve rated this material!

Got a project? Let's discuss it!

    Kyiv Sofiivska 1/2a, 01001, Kyiv, Ukraine
    Dnipro Hlinky 2, of. 1003, 49000, Dnipro, Ukraine
    Kharkiv Otakara Yarosha 22, 61000, Kharkiv, Ukraine