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?
In a Rails app, logs are stored under the /log folder. In development mode, the development. log file is used & you see log output on the terminal you're running rails server on.
To write in the current log use the logger. (debug|info|warn|error|fatal|unknown) method from within a controller, model, or mailer: logger. debug "Person attributes hash: #{@person.
Ruby comes with two built-in options to handle logging: printing commands (specially designed for command-line scenarios) and the Logger class. Let's explore them a little bit. “We've looked at a lot of error management systems.
Since the logger library comes with Ruby, there's no need to install any gems or other libraries. To begin using the logger library, simply require 'logger' and create a new Logger object. Any messages written to the Logger object will be written to the log file.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With