Michael Liu
Michael Liu

Reputation: 1131

Using logger in Rails 4

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.

Upvotes: 59

Views: 86183

Answers (4)

Ymox
Ymox

Reputation: 329

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

Upvotes: 0

Haseeb A
Haseeb A

Reputation: 6152

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'

Upvotes: 8

Kelsey Hannan
Kelsey Hannan

Reputation: 2967

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

Upvotes: 1

AnkitG
AnkitG

Reputation: 6568

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

Upvotes: 79

Related Questions