Using logger in Rails 4

2019-03-09 19:52发布

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.

4条回答
霸刀☆藐视天下
2楼-- · 2019-03-09 20:01

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
查看更多
女痞
3楼-- · 2019-03-09 20:14

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'
查看更多
贪生不怕死
4楼-- · 2019-03-09 20:16

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
查看更多
戒情不戒烟
5楼-- · 2019-03-09 20:17

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

查看更多
登录 后发表回答