Created
May 6, 2015 14:09
-
-
Save gareth/2b878d3b002f736dc19c to your computer and use it in GitHub Desktop.
Simple Ruby module to add configurable, class/instance level logging to any class
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 'logger' | |
# Adds configurable logger functionality to a class | |
# | |
# class Foo | |
# include Loggable | |
# | |
# def complicated_method | |
# logger.debug("Foo") { "Beginning long method" } | |
# sleep(2) | |
# logger.info("Foo") { "Long method finished" } | |
# end | |
# end | |
# | |
# Foo.logger = Logger.new(STDOUT) | |
# Foo.logger.level = Logger::INFO | |
# | |
# Foo.new.complicated_method | |
# | |
# #=> I, [2015-05-06T14:59:59.788163 #8176] INFO -- Foo: Long method finished | |
module Loggable | |
def self.included(base) | |
base.extend ClassMethods | |
end | |
module ClassMethods | |
attr_writer :logger | |
def logger | |
@logger ||= Logger.new(nil) | |
end | |
end | |
def logger | |
self.class.logger | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment