How can I write to Rails logger within my gem How can I write to Rails logger within my gem ruby-on-rails ruby-on-rails

How can I write to Rails logger within my gem


As Frederick Cheung says, you should use a namespaced logger for your gem: MyGem.logger.

Then set it to the Rails logger in a Railtie so that your gem works nicely both inside and outside of Rails.

module MyGem  class Railties < ::Rails::Railtie    initializer 'Rails logger' do      MyGem.logger = Rails.logger    end  endend


While you should be able to use Rails.logger you might want to consider making the logger that your gem uses configurable, i.e. allow users to set MyGem.logger to whatever logger they want.

You can default it to something that just writes to stdout, in a rails app you can set MyGem.logger = Rails.logger in an initialiser. People who are using your gem outside of rails can do so too.