Provide separate Rails log files for each Unicorn worker

Here's a snippet we're using to keep our Rails 4 Unicorn log files in separate files (one per Unicorn process) so that tools like Splunk can parse a single request as an atomic chunk. If you don't do this then the log files become interwoven with each other, making it very difficult for tools like Splunk to process your requests as atomic units.

In your unicorn config file:

after_fork do |server, worker|
  # This log hack provides separate log files for each unicorn worker.
  # Since Unicorn forks worker processes after loggers are already initialized, by this point other
  # things (like ActiveRecord::Base.logger) are already pointing directly at the current
  # Rails.logger instance so we can't just point `Rails.logger` elsewhere.
  logdev = Rails.logger.instance_variable_get(:@logdev)

  ext = File.extname(
  path = /#{Regexp.escape(ext)}$/, ".#{}#{ext}"

  # open the file in the same way rails does:
  file =, 'a')
  file.sync = Rails.application.config.autoflush_log
  logdev.instance_variable_set(:@dev, file)

Here is a gist.