Created
March 12, 2015 22:48
-
-
Save sebglazebrook/bf4fca6506b05bb666ed to your computer and use it in GitHub Desktop.
Method Logger Ruby
This file contains hidden or 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
require 'active_support' | |
# To use this make sure you add `include MethodLogger` at the END of your class definition | |
# Otherwise the methods you want aliased are not declared yet. | |
module MethodLogger | |
def self.logger | |
@@logger ||= Logger.new("#{Rails.root}/log/method_logger.log") | |
end | |
def self.included(base) | |
methods_to_log = base.instance_methods(false) - methods | |
logger.info "Logging methods: #{methods_to_log}" | |
base.class_eval do | |
methods_to_log.each do |method_name| | |
define_method("#{method_name}_with_logging".to_sym) do |*args, &block| | |
logger.info "#{base}##{method_name} called with (#{args.inspect[0..100]})" | |
result = send("#{method_name}_without_logging".to_sym, *args, &block) | |
logger.info "=> #{result.inspect[0..100]}" | |
result | |
end | |
alias_method_chain(method_name.to_sym, :logging) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment