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

前端 未结 9 1271
栀梦
栀梦 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:32

    A decent option that works for me is to just add a fairly plain class to your app/models folder such as app/models/my_log.rb

    class MyLog
      def self.debug(message=nil)
        @my_log ||= Logger.new("#{Rails.root}/log/my.log")
        @my_log.debug(message) unless message.nil?
      end
    end
    

    then in your controller, or really almost anywhere that you could reference a model's class from within your rails app, i.e. anywhere you could do Post.create(:title => "Hello world", :contents => "Lorum ipsum"); or something similar you can log to your custom file like this

    MyLog.debug "Hello world"
    

提交回复
热议问题