Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Logging for code in the lib directory?

What is the best/easiest way to configure logging for code kept in the lib directory?

like image 267
drt Avatar asked Jun 05 '10 13:06

drt


People also ask

Where can I see rails logs?

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.

What is log file in rails?

log file. Rails uses six different log levels: debug, info, warn, error, fatal, and unknown. Each level defines how much information your application will log: Debug: diagnostic information for developers and system administrators, including database calls or inspecting object attributes.

What is rails logger debugging?

logger. debug , or in short logger. debug writes the parameter text to a log file. This log file is by default environment specific. If you are currently running rails in development environment then the log file in use is log/development.


2 Answers

There's two ways to go about it:

  • Assuming your library is self-contained and has a module, you can add a logger attribute to your module and use that everywhere in your library code.

    module MyLibrary   mattr_accessor :logger end 

    You then either use an initializer in config/initializers/, or an config.after_initialize block in config/environment.rb to initialize your logger, like so:

    require 'mylibrary' MyLibrary.logger = Rails.logger 

    This would still allow you to use your self-contained library from scripts outside of Rails. Which is nice, on occasion.

  • If using your library without Rails really doesn't make sense at all, then you can also just use Rails.logger directly.

In either case, you're dealing with a standard Ruby Logger. Also keep in mind that, in theory, the logger may be nil.

like image 92
Stéphan Kochen Avatar answered Oct 13 '22 02:10

Stéphan Kochen


We can use Rails logger directly into the lib, see the following snippet.

require 'logger'  Rails.logger.info "Hay..!!! Im in lib" Rails.logger.debug "Debugging this object from Lib #{object.inspect}" Rails.logger.error "This is an error..." 
like image 32
Nadeem Yasin Avatar answered Oct 13 '22 01:10

Nadeem Yasin