Skip to content

Instantly share code, notes, and snippets.

@benoist
Forked from indirect/better_logger.rb
Created September 10, 2011 07:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benoist/1208084 to your computer and use it in GitHub Desktop.
Save benoist/1208084 to your computer and use it in GitHub Desktop.
Rails 3 logs with severity and PIDs
# You must require this file in application.rb, above the Application
# definition, for this to work. For example:
#
# # PIDs prepended to logs
# if Rails.env.production?
# require File.expand_path('../../lib/pid_logger', __FILE__)
# end
#
# module MyApp
# class Application < Rails::Application
require 'active_support/buffered_logger'
class PidLogger < ActiveSupport::BufferedLogger
SEVERITIES = Severity.constants.sort_by{|c| Severity.const_get(c) }
def add(severity, message = nil, progname = nil, &block)
return if @level > severity
message = (message || (block && block.call) || progname).to_s
# If a newline is necessary then create a new message ending with a newline.
# Ensures that the original message is not mutated.
message = "#{message}\n" unless message[-1] == ?\n
message.gsub!(/^(.+)/, "[#{$$}] #{SEVERITIES[severity]} \\1")
buffer << message
auto_flush
message
end
class Railtie < ::Rails::Railtie
initializer "swap in PidLogger" do
path = Rails.application.config.paths.log.first
level = Rails.logger.level
Rails.logger = PidLogger.new(path, level)
ActiveSupport::Dependencies.logger = Rails.logger
Rails.cache.logger = Rails.logger
ActiveSupport.on_load(:active_record) do
ActiveRecord::Base.logger = Rails.logger
end
ActiveSupport.on_load(:action_controller) do
ActionController::Base.logger = Rails.logger
end
ActiveSupport.on_load(:action_mailer) do
ActionMailer::Base.logger = Rails.logger
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment