Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share global logger among module/classes

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?

like image 367
cpjolicoeur Avatar asked Nov 05 '09 16:11

cpjolicoeur


2 Answers

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.

like image 113
Pesto Avatar answered Sep 27 '22 22:09

Pesto


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
like image 42
Mereghost Avatar answered Sep 27 '22 21:09

Mereghost