开发者

Share global logger among module/classes

开发者 https://www.devze.com 2022-12-11 03:27 出处:网络
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

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 th开发者_运维百科e 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?


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号