I've inherited a large pile of Ruby code that's, frankly, close to impossible to understand for a mortal like myself. It's actually Rspec unit test code, but the structure is "highly unusual" to put it nicely.
What I'd like to be able to do is run the code, and have the following information logged somewhere:
- every method that gets invoked, including the name of the class that defines the method, and the filename where the invoked method has been defined (yep, we've got the same class/method defined in multiple different files, and it's tough to know which is being invoked)
- (optionally) the parameters passed to each method invoked
With that, I could start trying to refactor it. Without it, it's going to be a very difficult task to get it straightened out, due to the size of the code base (20k+ unit test cases).
I can't afford to go in and perform wholesale edits to the code being run, because it breaks when you even use harsh language around it (i.e. frequently). Instead, I need to be able to instrument the code in its existing state, or with minimal changes to what exists now.
Is there a way of logging this level of detail without making wholesale changes to the code base? I've had a look at the Ruby profiler to see if it could help, and it probably could; I'm curious if there's a better way (particularly logging the filename containing the invoked method).
Thanks in advance
I wanted to include the seconds-past-the-minute the event happend at as well as how long was spent in each function
I was trying to debug why it took so long to create users and log into ActiveAdmin.
And from that I know Ruby spent more than a minute in
__bc_crypt
.This is definitely possible -- in fact, there's even a method for it! Just add this somewhere in your code before the point that you want to start logging things:
The secret sauce you want comes from
Kernel#set_trace_func
, as noted above:Here's a handy example:
(Note: don't try this in
irb
unless you want a huge scrolling screen of text.) The resulting output is:You can play around with the formatting string above to get just the results you want to log (for example, it sounds like you're only interested in
call
events). Hope that helps, and good luck with sorting through all those unit tests!Recently,
set_trace_func
was deprecated:We can use TracePoint, which backs
set_trace_func
, instead:This is actually even more powerful than
set_trace_func
because you can enable and disable at your convenience. You can selectively hook into the following events::line, :class, :end, :call, :return, :c_call, :c_return, :raise, :b_call, :b_return, :thread_begin, :thread_end
Here a full example: