Created
February 11, 2010 20:48
-
-
Save apeiros/301936 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env ruby | |
require 'logger' # requires belong *outside* | |
module LogInterceptors | |
LOGGER = Logger.new(STDOUT) | |
LOGGER.level = Logger::DEBUG | |
def log_all | |
log /.*/ | |
end | |
def log regex | |
raise "parameter must be of type Regexp ( just do /regex/ )" unless regex.is_a? Regexp | |
mod = Module.new | |
extend mod | |
class_str = to_s | |
methods.each do |m| | |
if m.to_s.match regex | |
mod.send(:define_method, m) do |*a| | |
start = Time.now | |
result = super | |
LOGGER.debug "#{class_str}: #{m}(#{a.map { |arg| arg.inspect }.join(', ')}): #{Time.now - start}" | |
result | |
end | |
end | |
end | |
end | |
end | |
class Interceptors::Example | |
# you must include LogInterceptor to use it | |
extend LogInterceptors | |
# you can log every method call, be it a class method call | |
log_all | |
def initialize | |
# or a instance method call. You can even log only specific methods based on regular expressions | |
log /test/ | |
end | |
def test | |
puts "a test" | |
end | |
end | |
Interceptors::Example.new |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment