views:

167

answers:

2

What is the best (proper) way to share a logger instance amongst many ruby classes?

Right now I just created the logger as a global $logger = Logger.new variable, but I have a feeling that there is a better way to do this without using a global var.

If I have the following:

module Foo
  class A
  class B
  class C
  ...
  class Z
end

what is the best way to share a logger instances among all the classes? Do I declare/create the logger in the Foo module somehow or is just using the global $logger fine?

+1  A: 

Add a constant in the module:

module Foo
  Logger = Logger.new
  class A
  class B
  class C
  ...
  class Z
end

Then you can do Logger.log('blah') in your classes. Since we're shadowing the global constant Logger with Foo::Logger, this means that if you want to refer to the Logger class within the Foo module, you have to use the scope resolution: ::Logger.

Pesto
+2  A: 

You could create a singleton Logger for your app, so every reference will be to the same object.

require 'singleton'

class Logger
  include Singleton
end

l = Logger.instance
k = Logger.instance

puts k.object_id == l.object_id #returns true
Mereghost