9

Is there an easy way to log all method calls in a Rails app?

My main use for this would be in testing (and in debugging tests). I want to have more of a history than a stacktrace provides (for instance, when running rspec with the '-b' option).

3 Answers 3

19

It's easy to do. Just add 5 lines of code into your script/server:

#!/usr/bin/env ruby
set_trace_func proc {
  |event, file, line, id, binding, classname| 
  if event == "call" or event == "return" 
    printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
  end
}

require File.expand_path('../../config/boot',  __FILE__)
require 'commands/server'

It's described at http://phrogz.net/ProgrammingRuby/ospace.html#tracingyourprogramsexecution

Your application will become quite slow and you might get more output than you want. You can easily add more conditions on file/class/function names to avoid printing unwanted stuff.

3

Perftools might give you what you're looking for. It analyzes the entire process and can give you a graphical view that looks something like this. Rack perftools profiler is a rubygem that uses perftools and makes it easy to integrate with a Rails application, so I would recommend going with that if you want to try it.

-3

Firstly stacktrace IS every method call that was on the stack at the time an error occurred, what other history could you want besides this?

Secondly, to answer your question, no there is no easy way to log all method calls. You could up your log level all the way to debug which should give you more stuff in the logs, but this will only be things that someone has actually chosen to log, unrelated to method calls.

It probably wouldn't be that difficult to patch ruby in such a way that every method call will print some log statements before and after the method execution, but this will once again be similar to what a stack trace would give you anyway and potentially less since you won't get line numbers etc.

If you want more info than the stack trace, logging is the way most people would do it.

1
  • I definitely mean the history of what happened before what is on the stacktrace. Practically, I am switching from declarative_authorization to cancan in a rails app, and suddenly a bunch of my 'should_receive' in my rspec tests no longer work, though the db-calls in the log look fine. I think if I know what calls changed, I can update my tests and be on my merry way.
    – dafmetal
    Aug 13, 2011 at 16:25

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.