开发者

Separating rails logs per action

开发者 https://www.devze.com 2023-03-15 19:19 出处:网络
I have rails 3 app that generates a lot of requests for analytics. 开发者_开发百科Unfortunately this drowns the logs and I lose the main page requests that I actually care about. I want to separate th

I have rails 3 app that generates a lot of requests for analytics. 开发者_开发百科Unfortunately this drowns the logs and I lose the main page requests that I actually care about. I want to separate these requests in to a separate log file. Is there a way to specify certain actions to go to a certain log file? Or possibly a way to reduce the logging level of these actions, and then only show certain level logs when reading back the log file?


I found this site, which talked about using a middleware for silencing log actions. I used the same sort of idea and ended up writing a middleware that would swap the logger depending on which action was being called. Here is the middleware, which i put in lib/noisy_logger.rb

class NoisyLogger < Rails::Rack::Logger
  def initialize app, opts = {}
    @default_log = Rails.logger

    # Put the noisy log in the same directory as the default log.
    @noisy_log = Logger.new Rails.root.join('log', 'noisy.log')

    @app = app
    @opts = opts
    @opts[:noisy] = Array @opts[:noisy]

    super app
  end

  def call env
    if @opts[:noisy].include? env['PATH_INFO']
      logfile = @noisy_log
    else
      logfile = @default_log
    end

    # What?! Why are these all separate?
    ActiveRecord::Base.logger = logfile
    ActionController::Base.logger = logfile
    Rails.logger = logfile

    # The Rails::Rack::Logger class is responsible for logging the
    # 'starting GET blah blah' log line. We need to call super here (as opposed
    # to @app.call) to make sure that line gets output. However, the
    # ActiveSupport::LogSubscriber class (which Rails::Rack::Logger inherits
    # from) caches the logger, so we have to override that too
    @logger = logfile

    super
  end
end

And then this goes in config/initializers/noisy_log.rb

MyApp::Application.config.middleware.swap(
  Rails::Rack::Logger, NoisyLogger, :noisy => "/analytics/track"
)

Hope that helps someone!


One option could be using a service like New Relic which would give you the required scoping (per action).

0

精彩评论

暂无评论...
验证码 换一张
取 消