Skip to content

Instantly share code, notes, and snippets.

@benjamin-thomas
Last active August 29, 2015 14:02
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 benjamin-thomas/0393c2eccbe08e424857 to your computer and use it in GitHub Desktop.
Save benjamin-thomas/0393c2eccbe08e424857 to your computer and use it in GitHub Desktop.
Shared logger setup
require 'logger'
require 'singleton'
module Logging
def logger
Logger.instance
end
class Logger < ::Logger
include Singleton
def initialize
puts 'Initializing logger...'
super(STDOUT)
self.level = Logger::INFO
self
end
end
end
class Animal
include Logging
def talk(sound)
puts "#{sound}!!"
logger.info(self.class) do
"Said #{sound}, object_id = #{object_id}, logger_object_id = #{logger.object_id}"
end
end
end
class Dog < Animal
def bark
talk 'Woof'
end
end
class Cat < Animal
def meow
talk 'Meow'
end
end
dog1, dog2 = 2.times.map { Dog.new }
cat1, cat2 = 2.times.map { Cat.new }
dog1.bark # Initializes the logger, once
dog2.bark # Uses the same logger instance
cat1.meow # Same
cat2.meow # Etc.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment