Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write log inside my rubygem that will be used in a rails app?

I'm developing a rubygem that will be used in a rails app. In this rubygem i need to log some information (warnings, errors...).

I saw some gems to do this, like logging, but apparently i need no configure the log output (stdout, some file).
My rails app log the messages in a file. So, my question: Is there a way to my gem use the same log configuration that my rails app uses? or my gem will send the log according to his own configuration?

like image 955
Victor Avatar asked Jun 03 '15 14:06

Victor


People also ask

Where are rails logs stored?

In a Rails app, logs are stored under the /log folder.

Where does Rails logger info write to?

By default it puts these log files in the log/ directory of your project. So if you open up that folder you'll see a development.


1 Answers

You may use Rails.logger directly, which is valid if your gem will always only be used within a Rails application. You may alternatively define a logger for your gem namespace and default to Rails.logger if defined, or Logger.new(STDOUT) if it's not, along with a writer, so it's overridable:

module MyGem
  def self.logger
    @@logger ||= defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
  end

  def self.logger=(logger)
    @@logger = logger
  end
end

Whatever the case, you will use it like this:

MyGem.logger.debug "it works"
like image 164
Julien Portalier Avatar answered Nov 16 '22 01:11

Julien Portalier