Using logger in Rails 4

LoggingRuby on-Rails-4

Logging Problem Overview


I'm working on a Rails 4 project, and I can't seem to make anything show up in my development log when I call Rails.logger.debug "test" I've tried searching online but I feel like I haven't made much progress. How would I go about setting up a logger and telling it to write in my development log file?

Any help would be greatly appreciated.

Logging Solutions


Solution 1 - Logging

I think you should use it like this in your method. Checkout section 2.3 here

def your_method  
  logger.debug "This is from debug"
  logger.info "This is from info"
end

Solution 2 - Logging

rails has an easy logging mechanism

from inside controller/model

logger.info 'some info'
logger.error 'some error'

etc.

From Outside these Rails's sections, in Plain Old Ruby objects such as service objects, library objects, you can easily access the same default logger

for rails < 3

logger = RAILS_DEFAULT_LOGGER
logger.info 'some info'
logger.error 'some error'

for rails > 3

logger = Rails.logger
logger.info 'some info'
logger.error 'some error'

Solution 3 - Logging

If you want to use Rails.logger in a Plain Old Ruby Object or ServiceObject, then you will need to include it manually:

class MyService
  def initialize(foo)
    @logger = Logger.new(STDOUT)
    @foo = foo
  end

  def call
    do_something
  end

  private
  
  def do_something
    @logger.debug { "do_something called! With #{@foo.class} class" }
  end
end

Result:

MyService.new(Bar.new).call
# [2018-01-27T00:17:22.167974 #57866] DEBUG -- : do_something called! With Bar class

Solution 4 - Logging

If no logger output appears in your log file, then check to what value log_level has been set in your environments file (config/environments/development.rb, ...) It should either not bee there (default is :debug) or

config.log_level = :debug

should be set. Other values are:

:debug, :info, :warn, :error, :fatal, :unknown

More information here: https://guides.rubyonrails.org/debugging_rails_applications.html section 2.2 Log levels

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael LiuView Question on Stackoverflow
Solution 1 - LoggingAnkitGView Answer on Stackoverflow
Solution 2 - LoggingHaseeb AView Answer on Stackoverflow
Solution 3 - LoggingKelsey HannanView Answer on Stackoverflow
Solution 4 - LoggingYmoxView Answer on Stackoverflow