TracePoint API – what is it?

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

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
    end

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

  end
end

 

… 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!

*By submitting this form you agree with our Privacy Policy.

Mailing & Legal Address

Syndicode Inc. 340 S Lemon Ave #3299, Walnut CA, 91789, USA

Visiting & Headquarters address
Kyiv Sofiivska 1/2a, 01001, Kyiv, Ukraine
Dnipro Hlinky 2, of. 1003, 49000, Dnipro, Ukraine
Email info@syndicode.com
Phone (+1) 9035021111