Reputation: 1461
I have a gem which I wrote and I use it inside my rails application.
I want to write to rails logger from my gem but obviously the standard rails logger doesn't exist there.
What is the right way to achieve what I want to do?
Upvotes: 11
Views: 4846
Reputation: 511
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
end
end
Upvotes: 15
Reputation: 84172
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.
Upvotes: 8