Search code examples
ruby-on-railsrubytestinglibraries

How to make logging in rails libs works like in models and controllers


So far I always used "puts" to add custom logging infos to my code. But now it is kind of a pain. When I run rspec for exemple I'm not interested in all the verbose that I added with puts. So I installed the "logging and logging-rails gem" because its installation is real fast and satisfying.

It works well when I call logger from models and controller, but not when I'm using logger inside libraries. I get that error : NameError - undefined local variable or method `logger' for CustomLib:Class.

The easiest thing I succeeded is to call 'Rails.logger' instead of just 'logger'. But in that way in my logfile, the class referring to that line will be 'Rails' but I want 'CustomLib'. For models and controller the right classname is displayed without any intervention from myself.

  # config/environnement/test.rb

  # Set the logging destination(s)
  config.log_to = %w[stdout]
  config.log_level = :info

  # Show the logging configuration on STDOUT
  config.show_log_configuration = false
  # lib/custom_lib.rb
  class CustomLib
    def initialize
      Rails.logger.info 'foo'
    end
  end

When I will use or test my customlib class I'll get : [2019-06-21T16:26:41] INFO Rails : foo

Instead I would like to see : [2019-06-21T16:26:41] INFO CustomLib : foo

I'm a bit lost in all that log management in rails, I have no idea what to try next to reach that goal...

 Edit

When I put a byebug just before the "logger.info 'foo' " line and enter into it via 'step', I got two different results if whether I'm in a model/controller or a custom lib.

# In custom lib, step enters this file "gems/logging-2.2.2/lib/logging/logger.rb"
# And Rails.logger returns an object like this one beloow
Logging::Logger:0x000055a2182f8f40
  @name="Rails",
  @parent=#<Logging::RootLogger:0x000055a2182e7ee8 
    @name="root",
    @level=1>,

# In model/controller, step enters this file "gems/logging-rails-0.6.0/lib/logging/rails/mixin.rb"
# And Rails.logger returns an object like this one beloow
Logging::Logger:0x0000557aed75d7b8
  @name="Controller",
  @parent=#<Logging::RootLogger:0x0000557aedfcf630
    @name="root",
    @level=0>,

Solution

  • At the end I found a better way, I just need to include Logging.globally on top of the module where I want that behavior:

    # lib/custom_lib.rb
    class CustomLib
      include Logging.globally
     
      def initialize
        logger.info 'foo'
      end
    end