Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write to Rails logger within my gem

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?

like image 342
gilsilas Avatar asked Jan 01 '12 12:01

gilsilas


People also ask

Where does Rails logger write to?

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.

How do you write logs in rails?

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.

How do I log data in Ruby?

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.

How do I create a log file in Ruby?

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.


2 Answers

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
like image 150
Jesse Storimer Avatar answered Oct 09 '22 14:10

Jesse Storimer


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.

like image 35
Frederick Cheung Avatar answered Oct 09 '22 14:10

Frederick Cheung