Created
September 6, 2012 12:58
-
-
Save nhance/3655996 to your computer and use it in GitHub Desktop.
Rails compatible method logging. Use this to log all calls to instance methods of a class to the log.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Model.new.foo |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module MethodLogger | |
def self.included(base) | |
methods = base.instance_methods(false) + base.private_instance_methods(false) | |
base.class_eval do | |
methods.each do |method_name| | |
original_method = instance_method(method_name) | |
define_method(method_name) do |*args, &block| | |
Rails.logger.info "-> #{base}##{method_name}(#{args.inspect})" | |
return_value = original_method.bind(self).call(*args, &block) | |
Rails.logger.info "<- #{base}##{method_name} #=> #{return_value.inspect}" | |
return_value | |
end | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Model | |
include MethodLogging | |
def foo | |
"bar" | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-> foo([]) | |
<- foo #=> "bar" |
Doesn't self.included
only know about the methods above it? Wouldn't it have to be included at the bottom of model.rb for it to see foo
?
Could also checkout https://github.com/ridiculous/object_tracker for tracking all methods with execution time
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very handy. Thanks for sharing.
include MethodLogging
needs to beinclude MethodLogger
though.