Redirect logger output for a specific controller in Rails 4

坚强是说给别人听的谎言 提交于 2019-12-03 05:11:30

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.

lacostenycoder

I'm not sure if you need to approach the solution in the same way as you had done in Rails 3. It seems there may be other ways to accomplish your end goal. Have you considered any of these approaches or gems?

https://github.com/TwP/logging

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

Sometimes trying something completely different than what you've already done can be helpful IMHO.

This is a bit of guess, but this may be why your getter setters are not working as expected: https://github.com/rails/rails/commit/6329d9fa8b2f86a178151be264cccdb805bfaaac

Regarding Jagjot's solution and needing to set base log for each of the MVC Action Classes, Rails 4 sets these separately by default which would in tern seem to provide more flexibility out of the box. http://guides.rubyonrails.org/configuring.html#initializers

The approach of using a different logging class for 1 controller has the downside that it won't work on a threading server which is in fashion these days not just with JRuby, but MRI too thanks to Heroku

Only idea I have so far after giving it a week of thought is to pipe the logs to syslog and use syslog's facilities to split them into separate files.

It would still require patching the Logger to include strings that would allow for the splitting (such as adding a formatted lined of from the #caller trace to the log files).

Plan B would be to introduce my own logger and simply log what I need in that controller. You could easily dump params and response for example if that's enough

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!