Last active
August 29, 2015 14:17
-
-
Save IronSavior/009f3a41ffcbef95459d to your computer and use it in GitHub Desktop.
Convenient logging methods
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
# Author: Erik Elmore <[email protected]> | |
# License: Public Domain | |
# Convenience in logging | |
module LogMethods | |
def error( *args, &blk ) | |
log :error, *args, &blk | |
end | |
private :error | |
def warning( *args, &blk ) | |
log :warning, *args, &blk | |
end | |
private :warning | |
def info( *args, &blk ) | |
log :info, *args, &blk | |
end | |
private :info | |
def debug( *args, &blk ) | |
log :debug, *args, &blk | |
end | |
private :debug | |
def log_context | |
self.class | |
end | |
private :log_context | |
def log( level, msg = yield ) | |
raise ArgumentError, 'No message given' if msg.nil? || msg.empty? | |
log_write level, '[%s]: %s' % [log_context, msg] | |
end | |
private :log | |
def log_write( level, msg ) | |
puts '%s %s' % [level.to_s.upcase, msg] | |
end | |
private :log_write | |
end | |
# Demonstration | |
if $0 == __FILE__ | |
module Test | |
class Base | |
include LogMethods | |
def test | |
[:error, :warning, :info, :debug].each{ |m| | |
send m, 'Normal' | |
send(m){ 'Block (lazy-evaluated)' } | |
} | |
end | |
end | |
Noisy = Class.new Base | |
class Quiet < Base | |
def warning(*); end | |
def info(*); end | |
def debug(*); end | |
end | |
[Noisy, Quiet].each{ |c| | |
puts '*** %s' % c | |
c.new.test | |
puts | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment