Redirect logger output for a specific controller in Rails 4

前端 未结 3 830
栀梦
栀梦 2021-02-07 08:57

I\'ve built a solution based on the answer in my previous question Redirect logger output for a specific controller in Rails 3 for Rails 3. It works great however now I am tryin

3条回答
  •  名媛妹妹
    2021-02-07 09:43

    After hacking around the Rails code for a day, I think I have found a hack-ish solution to your problem.

    You need to edit the call method and initialize method as follow:

    def initialize(app)
      @app = app
      @logger = Rails.instance_variable_get(:@logger)
      @reports_api_controller_logger = Logger.new(
          Rails.root.join('log', REPORTS_API_CONTROLLER_LOGFILE),
          10, 1000000)
    end
    
    def call(env)
      if env['PATH_INFO'] =~ /api\/v.*\/reports.*/
        Rails.instance_variable_set(:@logger, @reports_api_controller_logger)
        ActionController::Base.logger = @reports_api_controller_logger
        ActiveRecord::Base.logger = @reports_api_controller_logger
        ActionView::Base.logger = @reports_api_controller_logger
      else
        Rails.instance_variable_set(:@logger, @logger)
        ActionController::Base.logger = @logger
        ActiveRecord::Base.logger = @logger
        ActionView::Base.logger = @logger
      end
      @app.call(env)
    end
    

    This is really a hack-ish solution and modify the regex according to your needs.

    Tell me if this doesn't work for you.

提交回复
热议问题