Take the 2-minute tour ×

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?

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

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

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

    # 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


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

  Rails::Rack::Logger, NoisyLogger, :noisy => "/analytics/track"

Hope that helps someone!

share|improve this answer
add comment

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

share|improve this answer
add comment

Your Answer


