user508458
user508458

Reputation:

What's the best way to prevent rails production logs from interleaving logging from different requests?

Prior to rails 3.2, this was prevented by default. With rails 3.2, there doesn't seem to be a clear-cut solution. In comments in the commit introducing the change, Aaron suggested tagging the log lines with process pid and/or request uuid, which doesn't satisfy our Operations folks. I've seen some random solutions hither and yon, but it's unclear how well they solve the problem. This seems like a fairly banal problem that everyone would have; what solutions do others recommend? Does everyone else just rely on NewRelic to log the data about which they care?

Aaron's Commit

Upvotes: 4

Views: 721

Answers (2)

robd
robd

Reputation: 9825

More info here: https://github.com/rails/rails/issues/5388

The answer above didn't flush the log lines after each request (Rails 3.2.18). So I used a initializer based on this post:

class NonInterleavedLoggingMiddleware
  def initialize(app, options = {})
    @log = Rails.logger
      .instance_variable_get(:@logger)
      .instance_variable_get(:@log)
      .instance_variable_get(:@logdev)
      .instance_variable_get(:@dev)
    @log.sync = false
    @app = app
  end

  def call(env)
    @app.call(env)
  ensure
    @log.flush # Rails.logger.flush has no effect / is deprecated
  end
end

YourAppName::Application.config.middleware.insert_before(Rails::Rack::Logger, NonInterleavedLoggingMiddleware)

Upvotes: 0

user508458
user508458

Reputation:

We ended up writing a mildly horrible patch to revert to the old behavior:

config.after_initialize do

  # Reverse the deprecation of flush in BufferedLogger
  module ActiveSupport
    class BufferedLogger
      def flush
        @log_dest.flush
      end
      def respond_to?(method, include_private = false)
        super
      end
    end
  end

  # Let the OS buffer the log
  Rails.logger.instance_variable_get(:@logger).instance_variable_get(:@log_dest).sync = false
end

Upvotes: 1

Related Questions