Skip to content

Instantly share code, notes, and snippets.

@gareth
Created May 6, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gareth/2b878d3b002f736dc19c to your computer and use it in GitHub Desktop.
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
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