How to log something in Rails in an independent log file?

前端 未结 9 1298
栀梦
栀梦 2020-11-30 17:12

In rails I want to log some information in a different log file and not the standard development.log or production.log. I want to do this logging from a model class.

9条回答
  •  时光说笑
    2020-11-30 17:38

    Define a logger class in (say) app/models/special_log.rb:

    class SpecialLog
      LogFile = Rails.root.join('log', 'special.log')
      class << self
        cattr_accessor :logger
        delegate :debug, :info, :warn, :error, :fatal, :to => :logger
      end
    end
    

    initialize the logger in (say) config/initializers/special_log.rb:

    SpecialLog.logger = Logger.new(SpecialLog::LogFile)
    SpecialLog.logger.level = 'debug' # could be debug, info, warn, error or fatal
    

    Anywhere in your app, you can log with:

    SpecialLog.debug("something went wrong")
    # or
    SpecialLog.info("life is good")
    

提交回复
热议问题