From 6788db824ab732b13493a9d702dd8fb89fa153c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Thu, 24 Jun 2010 13:23:43 +0200 Subject: Move Rails::LogSubscriber to ActiveSupport::LogSubscriber, allowing frameworks like ActiveRecord and ActiveResource to log outsude Rails::Application [#4816 state:resolved] --- actionmailer/lib/action_mailer/base.rb | 1 + actionmailer/lib/action_mailer/log_subscriber.rb | 22 ++++ actionmailer/lib/action_mailer/railtie.rb | 3 - .../lib/action_mailer/railties/log_subscriber.rb | 22 ---- actionmailer/test/log_subscriber_test.rb | 8 +- actionpack/lib/action_controller/base.rb | 2 + actionpack/lib/action_controller/log_subscriber.rb | 56 ++++++++++ actionpack/lib/action_controller/railtie.rb | 3 - .../action_controller/railties/log_subscriber.rb | 56 ---------- actionpack/lib/action_view/base.rb | 1 + actionpack/lib/action_view/log_subscriber.rb | 27 +++++ actionpack/lib/action_view/railtie.rb | 3 - .../lib/action_view/railties/log_subscriber.rb | 27 ----- .../test/activerecord/controller_runtime_test.rb | 10 +- actionpack/test/controller/log_subscriber_test.rb | 10 +- actionpack/test/template/log_subscriber_test.rb | 10 +- activerecord/lib/active_record/base.rb | 1 + activerecord/lib/active_record/log_subscriber.rb | 32 ++++++ activerecord/lib/active_record/railtie.rb | 3 - .../lib/active_record/railties/log_subscriber.rb | 32 ------ activerecord/test/cases/log_subscriber_test.rb | 9 +- activeresource/lib/active_resource/base.rb | 1 + .../lib/active_resource/log_subscriber.rb | 15 +++ activeresource/lib/active_resource/railtie.rb | 3 - .../lib/active_resource/railties/log_subscriber.rb | 15 --- activeresource/test/cases/log_subscriber_test.rb | 9 +- activesupport/lib/active_support.rb | 3 +- activesupport/lib/active_support/log_subscriber.rb | 114 +++++++++++++++++++ .../active_support/log_subscriber/test_helper.rb | 90 +++++++++++++++ activesupport/test/log_subscriber_test.rb | 123 +++++++++++++++++++++ railties/lib/rails.rb | 1 - railties/lib/rails/application/configuration.rb | 2 +- railties/lib/rails/log_subscriber.rb | 115 ------------------- railties/lib/rails/log_subscriber/test_helper.rb | 97 ---------------- railties/lib/rails/rack/logger.rb | 24 ++-- railties/lib/rails/railtie.rb | 34 +----- railties/test/log_subscriber_test.rb | 123 --------------------- 37 files changed, 528 insertions(+), 579 deletions(-) create mode 100644 actionmailer/lib/action_mailer/log_subscriber.rb delete mode 100644 actionmailer/lib/action_mailer/railties/log_subscriber.rb create mode 100644 actionpack/lib/action_controller/log_subscriber.rb delete mode 100644 actionpack/lib/action_controller/railties/log_subscriber.rb create mode 100644 actionpack/lib/action_view/log_subscriber.rb delete mode 100644 actionpack/lib/action_view/railties/log_subscriber.rb create mode 100644 activerecord/lib/active_record/log_subscriber.rb delete mode 100644 activerecord/lib/active_record/railties/log_subscriber.rb create mode 100644 activeresource/lib/active_resource/log_subscriber.rb delete mode 100644 activeresource/lib/active_resource/railties/log_subscriber.rb create mode 100644 activesupport/lib/active_support/log_subscriber.rb create mode 100644 activesupport/lib/active_support/log_subscriber/test_helper.rb create mode 100644 activesupport/test/log_subscriber_test.rb delete mode 100644 railties/lib/rails/log_subscriber.rb delete mode 100644 railties/lib/rails/log_subscriber/test_helper.rb delete mode 100644 railties/test/log_subscriber_test.rb diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index 44c7382f72..3b6e2c6387 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -4,6 +4,7 @@ require 'action_mailer/collector' require 'active_support/core_ext/array/wrap' require 'active_support/core_ext/object/blank' require 'active_support/core_ext/proc' +require 'action_mailer/log_subscriber' module ActionMailer #:nodoc: # Action Mailer allows you to send email from your application using a mailer model and views. diff --git a/actionmailer/lib/action_mailer/log_subscriber.rb b/actionmailer/lib/action_mailer/log_subscriber.rb new file mode 100644 index 0000000000..7ba57b19e0 --- /dev/null +++ b/actionmailer/lib/action_mailer/log_subscriber.rb @@ -0,0 +1,22 @@ +require 'active_support/core_ext/array/wrap' + +module ActionMailer + class LogSubscriber < ActiveSupport::LogSubscriber + def deliver(event) + recipients = Array.wrap(event.payload[:to]).join(', ') + info("\nSent mail to #{recipients} (%1.fms)" % event.duration) + debug(event.payload[:mail]) + end + + def receive(event) + info("\nReceived mail (%.1fms)" % event.duration) + debug(event.payload[:mail]) + end + + def logger + ActionMailer::Base.logger + end + end +end + +ActionMailer::LogSubscriber.attach_to :action_mailer \ No newline at end of file diff --git a/actionmailer/lib/action_mailer/railtie.rb b/actionmailer/lib/action_mailer/railtie.rb index 43a4936013..d7b09b2dc6 100644 --- a/actionmailer/lib/action_mailer/railtie.rb +++ b/actionmailer/lib/action_mailer/railtie.rb @@ -5,9 +5,6 @@ module ActionMailer class Railtie < Rails::Railtie config.action_mailer = ActiveSupport::OrderedOptions.new - require "action_mailer/railties/log_subscriber" - log_subscriber :action_mailer, ActionMailer::Railties::LogSubscriber.new - initializer "action_mailer.logger" do ActiveSupport.on_load(:action_mailer) { self.logger ||= Rails.logger } end diff --git a/actionmailer/lib/action_mailer/railties/log_subscriber.rb b/actionmailer/lib/action_mailer/railties/log_subscriber.rb deleted file mode 100644 index af76d807d0..0000000000 --- a/actionmailer/lib/action_mailer/railties/log_subscriber.rb +++ /dev/null @@ -1,22 +0,0 @@ -require 'active_support/core_ext/array/wrap' - -module ActionMailer - module Railties - class LogSubscriber < Rails::LogSubscriber - def deliver(event) - recipients = Array.wrap(event.payload[:to]).join(', ') - info("\nSent mail to #{recipients} (%1.fms)" % event.duration) - debug(event.payload[:mail]) - end - - def receive(event) - info("\nReceived mail (%.1fms)" % event.duration) - debug(event.payload[:mail]) - end - - def logger - ActionMailer::Base.logger - end - end - end -end diff --git a/actionmailer/test/log_subscriber_test.rb b/actionmailer/test/log_subscriber_test.rb index c08c34b4a2..ba9b4d6500 100644 --- a/actionmailer/test/log_subscriber_test.rb +++ b/actionmailer/test/log_subscriber_test.rb @@ -1,13 +1,13 @@ require "abstract_unit" -require "rails/log_subscriber/test_helper" -require "action_mailer/railties/log_subscriber" +require "active_support/log_subscriber/test_helper" +require "action_mailer/log_subscriber" class AMLogSubscriberTest < ActionMailer::TestCase - include Rails::LogSubscriber::TestHelper + include ActiveSupport::LogSubscriber::TestHelper def setup super - Rails::LogSubscriber.add(:action_mailer, ActionMailer::Railties::LogSubscriber.new) + ActionMailer::LogSubscriber.attach_to :action_mailer end class TestMailer < ActionMailer::Base diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 8611d0d3c3..a70ba0d2e3 100644 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -1,3 +1,5 @@ +require "action_controller/log_subscriber" + module ActionController class Base < Metal abstract! diff --git a/actionpack/lib/action_controller/log_subscriber.rb b/actionpack/lib/action_controller/log_subscriber.rb new file mode 100644 index 0000000000..ece270b3ce --- /dev/null +++ b/actionpack/lib/action_controller/log_subscriber.rb @@ -0,0 +1,56 @@ +require 'active_support/core_ext/object/blank' + +module ActionController + class LogSubscriber < ActiveSupport::LogSubscriber + INTERNAL_PARAMS = %w(controller action format _method only_path) + + def start_processing(event) + payload = event.payload + params = payload[:params].except(*INTERNAL_PARAMS) + + info " Processing by #{payload[:controller]}##{payload[:action]} as #{payload[:formats].first.to_s.upcase}" + info " Parameters: #{params.inspect}" unless params.empty? + end + + def process_action(event) + payload = event.payload + additions = ActionController::Base.log_process_action(payload) + + message = "Completed #{payload[:status]} #{Rack::Utils::HTTP_STATUS_CODES[payload[:status]]} in %.0fms" % event.duration + message << " (#{additions.join(" | ")})" unless additions.blank? + + info(message) + end + + def send_file(event) + message = "Sent file %s" + message << " (%.1fms)" + info(message % [event.payload[:path], event.duration]) + end + + def redirect_to(event) + info "Redirected to #{event.payload[:location]}" + end + + def send_data(event) + info("Sent data %s (%.1fms)" % [event.payload[:filename], event.duration]) + end + + %w(write_fragment read_fragment exist_fragment? + expire_fragment expire_page write_page).each do |method| + class_eval <<-METHOD, __FILE__, __LINE__ + 1 + def #{method}(event) + key_or_path = event.payload[:key] || event.payload[:path] + human_name = #{method.to_s.humanize.inspect} + info("\#{human_name} \#{key_or_path} (%.1fms)" % event.duration) + end + METHOD + end + + def logger + ActionController::Base.logger + end + end +end + +ActionController::LogSubscriber.attach_to :action_controller \ No newline at end of file diff --git a/actionpack/lib/action_controller/railtie.rb b/actionpack/lib/action_controller/railtie.rb index 0e3cdffadc..86395c4d93 100644 --- a/actionpack/lib/action_controller/railtie.rb +++ b/actionpack/lib/action_controller/railtie.rb @@ -6,7 +6,6 @@ require "active_support/core_ext/class/subclasses" require "active_support/deprecation/proxy_wrappers" require "active_support/deprecation" -require "action_controller/railties/log_subscriber" require "action_controller/railties/url_helpers" module ActionController @@ -35,8 +34,6 @@ module ActionController end end - log_subscriber :action_controller, ActionController::Railties::LogSubscriber.new - initializer "action_controller.set_configs" do |app| paths = app.config.paths ac = app.config.action_controller diff --git a/actionpack/lib/action_controller/railties/log_subscriber.rb b/actionpack/lib/action_controller/railties/log_subscriber.rb deleted file mode 100644 index 00ac3bdf67..0000000000 --- a/actionpack/lib/action_controller/railties/log_subscriber.rb +++ /dev/null @@ -1,56 +0,0 @@ -require 'active_support/core_ext/object/blank' - -module ActionController - module Railties - class LogSubscriber < Rails::LogSubscriber - INTERNAL_PARAMS = %w(controller action format _method only_path) - - def start_processing(event) - payload = event.payload - params = payload[:params].except(*INTERNAL_PARAMS) - - info " Processing by #{payload[:controller]}##{payload[:action]} as #{payload[:formats].first.to_s.upcase}" - info " Parameters: #{params.inspect}" unless params.empty? - end - - def process_action(event) - payload = event.payload - additions = ActionController::Base.log_process_action(payload) - - message = "Completed #{payload[:status]} #{Rack::Utils::HTTP_STATUS_CODES[payload[:status]]} in %.0fms" % event.duration - message << " (#{additions.join(" | ")})" unless additions.blank? - - info(message) - end - - def send_file(event) - message = "Sent file %s" - message << " (%.1fms)" - info(message % [event.payload[:path], event.duration]) - end - - def redirect_to(event) - info "Redirected to #{event.payload[:location]}" - end - - def send_data(event) - info("Sent data %s (%.1fms)" % [event.payload[:filename], event.duration]) - end - - %w(write_fragment read_fragment exist_fragment? - expire_fragment expire_page write_page).each do |method| - class_eval <<-METHOD, __FILE__, __LINE__ + 1 - def #{method}(event) - key_or_path = event.payload[:key] || event.payload[:path] - human_name = #{method.to_s.humanize.inspect} - info("\#{human_name} \#{key_or_path} (%.1fms)" % event.duration) - end - METHOD - end - - def logger - ActionController::Base.logger - end - end - end -end \ No newline at end of file diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index 50df1c97b2..956c88a553 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -3,6 +3,7 @@ require 'active_support/core_ext/module/delegation' require 'active_support/core_ext/class/attribute' require 'active_support/core_ext/array/wrap' require 'active_support/ordered_options' +require 'action_view/log_subscriber' module ActionView #:nodoc: class NonConcattingString < ActiveSupport::SafeBuffer diff --git a/actionpack/lib/action_view/log_subscriber.rb b/actionpack/lib/action_view/log_subscriber.rb new file mode 100644 index 0000000000..4a52937c58 --- /dev/null +++ b/actionpack/lib/action_view/log_subscriber.rb @@ -0,0 +1,27 @@ +module ActionView + # = Action View Log Subscriber + # + # Provides functionality so that Rails can output logs from Action View. + class LogSubscriber < ActiveSupport::LogSubscriber + def render_template(event) + message = "Rendered #{from_rails_root(event.payload[:identifier])}" + message << " within #{from_rails_root(event.payload[:layout])}" if event.payload[:layout] + message << (" (%.1fms)" % event.duration) + info(message) + end + alias :render_partial :render_template + alias :render_collection :render_template + + def logger + ActionController::Base.logger + end + + protected + + def from_rails_root(string) + string.sub("#{Rails.root}/", "").sub(/^app\/views\//, "") + end + end +end + +ActionView::LogSubscriber.attach_to :action_view \ No newline at end of file diff --git a/actionpack/lib/action_view/railtie.rb b/actionpack/lib/action_view/railtie.rb index 8c7b7d64c2..33dfcbb803 100644 --- a/actionpack/lib/action_view/railtie.rb +++ b/actionpack/lib/action_view/railtie.rb @@ -8,9 +8,6 @@ module ActionView config.action_view.stylesheet_expansions = {} config.action_view.javascript_expansions = { :defaults => ['prototype', 'effects', 'dragdrop', 'controls', 'rails'] } - require "action_view/railties/log_subscriber" - log_subscriber :action_view, ActionView::Railties::LogSubscriber.new - initializer "action_view.cache_asset_timestamps" do |app| unless app.config.cache_classes ActiveSupport.on_load(:action_view) do diff --git a/actionpack/lib/action_view/railties/log_subscriber.rb b/actionpack/lib/action_view/railties/log_subscriber.rb deleted file mode 100644 index cb2ad0711e..0000000000 --- a/actionpack/lib/action_view/railties/log_subscriber.rb +++ /dev/null @@ -1,27 +0,0 @@ -module ActionView - # = Action View Log Subscriber - # - # Provides functionality so that Rails can output logs from Action View. - module Railties - class LogSubscriber < Rails::LogSubscriber - def render_template(event) - message = "Rendered #{from_rails_root(event.payload[:identifier])}" - message << " within #{from_rails_root(event.payload[:layout])}" if event.payload[:layout] - message << (" (%.1fms)" % event.duration) - info(message) - end - alias :render_partial :render_template - alias :render_collection :render_template - - def logger - ActionController::Base.logger - end - - protected - - def from_rails_root(string) - string.sub("#{Rails.root}/", "").sub(/^app\/views\//, "") - end - end - end -end \ No newline at end of file diff --git a/actionpack/test/activerecord/controller_runtime_test.rb b/actionpack/test/activerecord/controller_runtime_test.rb index 331f861d8f..cfd86d704d 100644 --- a/actionpack/test/activerecord/controller_runtime_test.rb +++ b/actionpack/test/activerecord/controller_runtime_test.rb @@ -1,8 +1,8 @@ require 'active_record_unit' require 'active_record/railties/controller_runtime' require 'fixtures/project' -require 'rails/log_subscriber/test_helper' -require 'action_controller/railties/log_subscriber' +require 'active_support/log_subscriber/test_helper' +require 'action_controller/log_subscriber' ActionController::Base.send :include, ActiveRecord::Railties::ControllerRuntime @@ -13,18 +13,18 @@ class ControllerRuntimeLogSubscriberTest < ActionController::TestCase end end - include Rails::LogSubscriber::TestHelper + include ActiveSupport::LogSubscriber::TestHelper tests LogSubscriberController def setup super @old_logger = ActionController::Base.logger - Rails::LogSubscriber.add(:action_controller, ActionController::Railties::LogSubscriber.new) + ActionController::LogSubscriber.attach_to :action_controller end def teardown super - Rails::LogSubscriber.log_subscribers.clear + ActiveSupport::LogSubscriber.log_subscribers.clear ActionController::Base.logger = @old_logger end diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb index b11eba2f89..0a18741f0c 100644 --- a/actionpack/test/controller/log_subscriber_test.rb +++ b/actionpack/test/controller/log_subscriber_test.rb @@ -1,6 +1,6 @@ require "abstract_unit" -require "rails/log_subscriber/test_helper" -require "action_controller/railties/log_subscriber" +require "active_support/log_subscriber/test_helper" +require "action_controller/log_subscriber" module Another class LogSubscribersController < ActionController::Base @@ -37,7 +37,7 @@ end class ACLogSubscriberTest < ActionController::TestCase tests Another::LogSubscribersController - include Rails::LogSubscriber::TestHelper + include ActiveSupport::LogSubscriber::TestHelper def setup super @@ -47,12 +47,12 @@ class ACLogSubscriberTest < ActionController::TestCase @cache_path = File.expand_path('../temp/test_cache', File.dirname(__FILE__)) ActionController::Base.page_cache_directory = @cache_path @controller.cache_store = :file_store, @cache_path - Rails::LogSubscriber.add(:action_controller, ActionController::Railties::LogSubscriber.new) + ActionController::LogSubscriber.attach_to :action_controller end def teardown super - Rails::LogSubscriber.log_subscribers.clear + ActiveSupport::LogSubscriber.log_subscribers.clear FileUtils.rm_rf(@cache_path) ActionController::Base.logger = @old_logger end diff --git a/actionpack/test/template/log_subscriber_test.rb b/actionpack/test/template/log_subscriber_test.rb index 5076dfa70f..eb1e548672 100644 --- a/actionpack/test/template/log_subscriber_test.rb +++ b/actionpack/test/template/log_subscriber_test.rb @@ -1,22 +1,22 @@ require "abstract_unit" -require "rails/log_subscriber/test_helper" -require "action_view/railties/log_subscriber" +require "active_support/log_subscriber/test_helper" +require "action_view/log_subscriber" require "controller/fake_models" class AVLogSubscriberTest < ActiveSupport::TestCase - include Rails::LogSubscriber::TestHelper + include ActiveSupport::LogSubscriber::TestHelper def setup super @old_logger = ActionController::Base.logger @view = ActionView::Base.new(ActionController::Base.view_paths, {}) Rails.stubs(:root).returns(File.expand_path(FIXTURE_LOAD_PATH)) - Rails::LogSubscriber.add(:action_view, ActionView::Railties::LogSubscriber.new) + ActionView::LogSubscriber.attach_to :action_view end def teardown super - Rails::LogSubscriber.log_subscribers.clear + ActiveSupport::LogSubscriber.log_subscribers.clear ActionController::Base.logger = @old_logger end diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 7a262ad465..16cf501bd5 100644 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -20,6 +20,7 @@ require 'active_support/core_ext/object/duplicable' require 'active_support/core_ext/object/blank' require 'arel' require 'active_record/errors' +require 'active_record/log_subscriber' module ActiveRecord #:nodoc: # = Active Record diff --git a/activerecord/lib/active_record/log_subscriber.rb b/activerecord/lib/active_record/log_subscriber.rb new file mode 100644 index 0000000000..71065f9908 --- /dev/null +++ b/activerecord/lib/active_record/log_subscriber.rb @@ -0,0 +1,32 @@ +module ActiveRecord + class LogSubscriber < ActiveSupport::LogSubscriber + def initialize + super + @odd_or_even = false + end + + def sql(event) + name = '%s (%.1fms)' % [event.payload[:name], event.duration] + sql = event.payload[:sql].squeeze(' ') + + if odd? + name = color(name, :cyan, true) + sql = color(sql, nil, true) + else + name = color(name, :magenta, true) + end + + debug " #{name} #{sql}" + end + + def odd? + @odd_or_even = !@odd_or_even + end + + def logger + ActiveRecord::Base.logger + end + end +end + +ActiveRecord::LogSubscriber.attach_to :active_record \ No newline at end of file diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb index 36df878e1b..2808e199fe 100644 --- a/activerecord/lib/active_record/railtie.rb +++ b/activerecord/lib/active_record/railtie.rb @@ -26,9 +26,6 @@ module ActiveRecord load "active_record/railties/databases.rake" end - require "active_record/railties/log_subscriber" - log_subscriber :active_record, ActiveRecord::Railties::LogSubscriber.new - initializer "active_record.initialize_timezone" do ActiveSupport.on_load(:active_record) do self.time_zone_aware_attributes = true diff --git a/activerecord/lib/active_record/railties/log_subscriber.rb b/activerecord/lib/active_record/railties/log_subscriber.rb deleted file mode 100644 index 31b98bb6ed..0000000000 --- a/activerecord/lib/active_record/railties/log_subscriber.rb +++ /dev/null @@ -1,32 +0,0 @@ -module ActiveRecord - module Railties - class LogSubscriber < Rails::LogSubscriber - def initialize - super - @odd_or_even = false - end - - def sql(event) - name = '%s (%.1fms)' % [event.payload[:name], event.duration] - sql = event.payload[:sql].squeeze(' ') - - if odd? - name = color(name, :cyan, true) - sql = color(sql, nil, true) - else - name = color(name, :magenta, true) - end - - debug " #{name} #{sql}" - end - - def odd? - @odd_or_even = !@odd_or_even - end - - def logger - ActiveRecord::Base.logger - end - end - end -end diff --git a/activerecord/test/cases/log_subscriber_test.rb b/activerecord/test/cases/log_subscriber_test.rb index 1f544b4211..4aeae1fe45 100644 --- a/activerecord/test/cases/log_subscriber_test.rb +++ b/activerecord/test/cases/log_subscriber_test.rb @@ -1,20 +1,19 @@ require "cases/helper" require "models/developer" -require "rails/log_subscriber/test_helper" -require "active_record/railties/log_subscriber" +require "active_support/log_subscriber/test_helper" class LogSubscriberTest < ActiveSupport::TestCase - include Rails::LogSubscriber::TestHelper + include ActiveSupport::LogSubscriber::TestHelper def setup @old_logger = ActiveRecord::Base.logger super - - Rails::LogSubscriber.add(:active_record, ActiveRecord::Railties::LogSubscriber.new) + ActiveRecord::LogSubscriber.attach_to(:active_record) end def teardown super + ActiveRecord::LogSubscriber.log_subscribers.pop ActiveRecord::Base.logger = @old_logger end diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index 521e2b6f5d..6c494a8bcc 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -17,6 +17,7 @@ require 'active_resource/exceptions' require 'active_resource/connection' require 'active_resource/formats' require 'active_resource/schema' +require 'active_resource/log_subscriber' module ActiveResource # ActiveResource::Base is the main class for mapping RESTful resources as models in a Rails application. diff --git a/activeresource/lib/active_resource/log_subscriber.rb b/activeresource/lib/active_resource/log_subscriber.rb new file mode 100644 index 0000000000..9e52baf36d --- /dev/null +++ b/activeresource/lib/active_resource/log_subscriber.rb @@ -0,0 +1,15 @@ +module ActiveResource + class LogSubscriber < ActiveSupport::LogSubscriber + def request(event) + result = event.payload[:result] + info "#{event.payload[:method].to_s.upcase} #{event.payload[:request_uri]}" + info "--> %d %s %d (%.1fms)" % [result.code, result.message, result.body.to_s.length, event.duration] + end + + def logger + ActiveResource::Base.logger + end + end +end + +ActiveResource::LogSubscriber.attach_to :active_resource \ No newline at end of file diff --git a/activeresource/lib/active_resource/railtie.rb b/activeresource/lib/active_resource/railtie.rb index aa878c7212..60f6f88311 100644 --- a/activeresource/lib/active_resource/railtie.rb +++ b/activeresource/lib/active_resource/railtie.rb @@ -5,9 +5,6 @@ module ActiveResource class Railtie < Rails::Railtie config.active_resource = ActiveSupport::OrderedOptions.new - require "active_resource/railties/log_subscriber" - log_subscriber :active_resource, ActiveResource::Railties::LogSubscriber.new - initializer "active_resource.set_configs" do |app| app.config.active_resource.each do |k,v| ActiveResource::Base.send "#{k}=", v diff --git a/activeresource/lib/active_resource/railties/log_subscriber.rb b/activeresource/lib/active_resource/railties/log_subscriber.rb deleted file mode 100644 index 86806a93d0..0000000000 --- a/activeresource/lib/active_resource/railties/log_subscriber.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActiveResource - module Railties - class LogSubscriber < Rails::LogSubscriber - def request(event) - result = event.payload[:result] - info "#{event.payload[:method].to_s.upcase} #{event.payload[:request_uri]}" - info "--> %d %s %d (%.1fms)" % [result.code, result.message, result.body.to_s.length, event.duration] - end - - def logger - ActiveResource::Base.logger - end - end - end -end \ No newline at end of file diff --git a/activeresource/test/cases/log_subscriber_test.rb b/activeresource/test/cases/log_subscriber_test.rb index f0330e8f51..3cd96007db 100644 --- a/activeresource/test/cases/log_subscriber_test.rb +++ b/activeresource/test/cases/log_subscriber_test.rb @@ -1,12 +1,11 @@ require "abstract_unit" require "fixtures/person" -require "rails/log_subscriber/test_helper" -require "active_resource/railties/log_subscriber" +require "active_support/log_subscriber/test_helper" +require "active_resource/log_subscriber" require "active_support/core_ext/hash/conversions" -# TODO: This test should be part of Railties class LogSubscriberTest < ActiveSupport::TestCase - include Rails::LogSubscriber::TestHelper + include ActiveSupport::LogSubscriber::TestHelper def setup super @@ -16,7 +15,7 @@ class LogSubscriberTest < ActiveSupport::TestCase mock.get "/people/1.xml", {}, @matz end - Rails::LogSubscriber.add(:active_resource, ActiveResource::Railties::LogSubscriber.new) + ActiveResource::LogSubscriber.attach_to :active_resource end def set_logger(logger) diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb index 3ce5476bbd..ba91e8bba3 100644 --- a/activesupport/lib/active_support.rb +++ b/activesupport/lib/active_support.rb @@ -41,6 +41,8 @@ module ActiveSupport autoload :DescendantsTracker autoload :FileUpdateChecker + autoload :LogSubscriber + autoload :Notifications # TODO: Narrow this list down eager_autoload do @@ -64,7 +66,6 @@ module ActiveSupport autoload :OptionMerger autoload :OrderedHash autoload :OrderedOptions - autoload :Notifications autoload :Rescuable autoload :SecureRandom autoload :StringInquirer diff --git a/activesupport/lib/active_support/log_subscriber.rb b/activesupport/lib/active_support/log_subscriber.rb new file mode 100644 index 0000000000..a1ffb8eece --- /dev/null +++ b/activesupport/lib/active_support/log_subscriber.rb @@ -0,0 +1,114 @@ +require 'active_support/core_ext/module/attribute_accessors' +require 'active_support/core_ext/class/attribute' + +module ActiveSupport + # ActiveSupport::LogSubscriber is an object set to consume ActiveSupport::Notifications + # with solely purpose of logging. The log subscriber dispatches notifications to a + # regirested object based on its given namespace. + # + # An example would be Active Record log subscriber responsible for logging queries: + # + # module ActiveRecord + # class LogSubscriber < ActiveSupport::LogSubscriber + # def sql(event) + # "#{event.payload[:name]} (#{event.duration}) #{event.payload[:sql]}" + # end + # end + # end + # + # And it's finally registed as: + # + # ActiveRecord::LogSubscriber.attach_to :active_record + # + # Since we need to know all instance methods before attaching the log subscriber, + # the line above shuold be called after your ActiveRecord::LogSubscriber definition. + # + # After configured, whenever a "sql.active_record" notification is published, + # it will properly dispatch the event (ActiveSupport::Notifications::Event) to + # the sql method. + # + # Log subscriber also has some helpers to deal with logging and automatically flushes + # all logs when the request finishes (via action_dispatch.callback notification) in + # a Rails environment. + class LogSubscriber + mattr_accessor :colorize_logging + self.colorize_logging = true + + class_attribute :logger + + def self.logger + @logger ||= Rails.logger if defined?(Rails) + end + + # Embed in a String to clear all previous ANSI sequences. + CLEAR = "\e[0m" + BOLD = "\e[1m" + + # Colors + BLACK = "\e[30m" + RED = "\e[31m" + GREEN = "\e[32m" + YELLOW = "\e[33m" + BLUE = "\e[34m" + MAGENTA = "\e[35m" + CYAN = "\e[36m" + WHITE = "\e[37m" + + def self.attach_to(namespace, log_subscriber=new, notifier=ActiveSupport::Notifications) + log_subscribers << log_subscriber + @@flushable_loggers = nil + + log_subscriber.public_methods(false).each do |event| + notifier.subscribe("#{event}.#{namespace}") do |*args| + next if log_subscriber.logger.nil? + + begin + log_subscriber.send(event, ActiveSupport::Notifications::Event.new(*args)) + rescue Exception => e + log_subscriber.logger.error "Could not log #{args[0].inspect} event. #{e.class}: #{e.message}" + end + end + end + end + + def self.log_subscribers + @@log_subscribers ||= [] + end + + def self.flushable_loggers + @@flushable_loggers ||= begin + loggers = log_subscribers.map(&:logger) + loggers.uniq! + loggers.select { |l| l.respond_to?(:flush) } + end + end + + # Flush all log_subscribers' logger. + def self.flush_all! + flushable_loggers.each(&:flush) + end + + protected + + %w(info debug warn error fatal unknown).each do |level| + class_eval <<-METHOD, __FILE__, __LINE__ + 1 + def #{level}(*args, &block) + return unless logger + logger.#{level}(*args, &block) + end + METHOD + end + + # Set color by using a string or one of the defined constants. If a third + # option is set to true, it also adds bold to the string. This is based + # on Highline implementation and it automatically appends CLEAR to the end + # of the returned String. + # + def color(text, color, bold=false) + return text unless colorize_logging + color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol) + bold = bold ? BOLD : "" + "#{bold}#{color}#{text}#{CLEAR}" + end + end +end diff --git a/activesupport/lib/active_support/log_subscriber/test_helper.rb b/activesupport/lib/active_support/log_subscriber/test_helper.rb new file mode 100644 index 0000000000..96506a4b2b --- /dev/null +++ b/activesupport/lib/active_support/log_subscriber/test_helper.rb @@ -0,0 +1,90 @@ +require 'active_support/log_subscriber' + +module ActiveSupport + class LogSubscriber + # Provides some helpers to deal with testing log subscribers by setting up + # notifications. Take for instance Active Record subscriber tests: + # + # class SyncLogSubscriberTest < ActiveSupport::TestCase + # include ActiveSupport::LogSubscriber::TestHelper + # + # def setup + # ActiveRecord::LogSubscriber.attach_to(:active_record) + # end + # + # def test_basic_query_logging + # Developer.all + # wait + # assert_equal 1, @logger.logged(:debug).size + # assert_match /Developer Load/, @logger.logged(:debug).last + # assert_match /SELECT \* FROM "developers"/, @logger.logged(:debug).last + # end + # end + # + # All you need to do is to ensure that your log subscriber is added to Rails::Subscriber, + # as in the second line of the code above. The test helpers is reponsible for setting + # up the queue, subscriptions and turning colors in logs off. + # + # The messages are available in the @logger instance, which is a logger with limited + # powers (it actually do not send anything to your output), and you can collect them + # doing @logger.logged(level), where level is the level used in logging, like info, + # debug, warn and so on. + # + module TestHelper + def setup + @logger = MockLogger.new + @notifier = ActiveSupport::Notifications::Notifier.new(queue) + + ActiveSupport::LogSubscriber.colorize_logging = false + + set_logger(@logger) + ActiveSupport::Notifications.notifier = @notifier + end + + def teardown + set_logger(nil) + ActiveSupport::Notifications.notifier = nil + end + + class MockLogger + attr_reader :flush_count + + def initialize + @flush_count = 0 + @logged = Hash.new { |h,k| h[k] = [] } + end + + def method_missing(level, message) + @logged[level] << message + end + + def logged(level) + @logged[level].compact.map { |l| l.to_s.strip } + end + + def flush + @flush_count += 1 + end + end + + # Wait notifications to be published. + def wait + @notifier.wait + end + + # Overwrite if you use another logger in your log subscriber: + # + # def logger + # ActiveRecord::Base.logger = @logger + # end + # + def set_logger(logger) + ActiveSupport::LogSubscriber.logger = logger + end + + def queue + ActiveSupport::Notifications::Fanout.new + end + end + end +end \ No newline at end of file diff --git a/activesupport/test/log_subscriber_test.rb b/activesupport/test/log_subscriber_test.rb new file mode 100644 index 0000000000..0c1f3c51ed --- /dev/null +++ b/activesupport/test/log_subscriber_test.rb @@ -0,0 +1,123 @@ +require 'abstract_unit' +require 'active_support/log_subscriber/test_helper' + +class MyLogSubscriber < ActiveSupport::LogSubscriber + attr_reader :event + + def some_event(event) + @event = event + info event.name + end + + def foo(event) + debug "debug" + info "info" + warn "warn" + end + + def bar(event) + info "#{color("cool", :red)}, #{color("isn't it?", :blue, true)}" + end + + def puke(event) + raise "puke" + end +end + +class SyncLogSubscriberTest < ActiveSupport::TestCase + include ActiveSupport::LogSubscriber::TestHelper + + def setup + super + @log_subscriber = MyLogSubscriber.new + end + + def teardown + super + ActiveSupport::LogSubscriber.log_subscribers.clear + end + + def instrument(*args, &block) + ActiveSupport::Notifications.instrument(*args, &block) + end + + def test_proxies_method_to_rails_logger + @log_subscriber.foo(nil) + assert_equal %w(debug), @logger.logged(:debug) + assert_equal %w(info), @logger.logged(:info) + assert_equal %w(warn), @logger.logged(:warn) + end + + def test_set_color_for_messages + ActiveSupport::LogSubscriber.colorize_logging = true + @log_subscriber.bar(nil) + assert_equal "\e[31mcool\e[0m, \e[1m\e[34misn't it?\e[0m", @logger.logged(:info).last + end + + def test_does_not_set_color_if_colorize_logging_is_set_to_false + @log_subscriber.bar(nil) + assert_equal "cool, isn't it?", @logger.logged(:info).last + end + + def test_event_is_sent_to_the_registered_class + ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber + instrument "some_event.my_log_subscriber" + wait + assert_equal %w(some_event.my_log_subscriber), @logger.logged(:info) + end + + def test_event_is_an_active_support_notifications_event + ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber + instrument "some_event.my_log_subscriber" + wait + assert_kind_of ActiveSupport::Notifications::Event, @log_subscriber.event + end + + def test_does_not_send_the_event_if_it_doesnt_match_the_class + ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber + instrument "unknown_event.my_log_subscriber" + wait + # If we get here, it means that NoMethodError was not raised. + end + + def test_does_not_send_the_event_if_logger_is_nil + ActiveSupport::LogSubscriber.logger = nil + @log_subscriber.expects(:some_event).never + ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber + instrument "some_event.my_log_subscriber" + wait + end + + def test_does_not_fail_with_non_namespaced_events + ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber + instrument "whatever" + wait + end + + def test_flushes_loggers + ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber + ActiveSupport::LogSubscriber.flush_all! + assert_equal 1, @logger.flush_count + end + + def test_flushes_the_same_logger_just_once + ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber + ActiveSupport::LogSubscriber.attach_to :another, @log_subscriber + ActiveSupport::LogSubscriber.flush_all! + wait + assert_equal 1, @logger.flush_count + end + + def test_logging_does_not_die_on_failures + ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber + instrument "puke.my_log_subscriber" + instrument "some_event.my_log_subscriber" + wait + + assert_equal 1, @logger.logged(:info).size + assert_equal 'some_event.my_log_subscriber', @logger.logged(:info).last + + assert_equal 1, @logger.logged(:error).size + assert_equal 'Could not log "puke.my_log_subscriber" event. RuntimeError: puke', @logger.logged(:error).last + end +end \ No newline at end of file diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb index ed66f493e6..bbf28a8c08 100644 --- a/railties/lib/rails.rb +++ b/railties/lib/rails.rb @@ -9,7 +9,6 @@ require 'active_support/core_ext/logger' require 'rails/application' require 'rails/version' require 'rails/deprecation' -require 'rails/log_subscriber' require 'active_support/railtie' require 'action_dispatch/railtie' diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb index 25e54e9dce..e3165b2d4c 100644 --- a/railties/lib/rails/application/configuration.rb +++ b/railties/lib/rails/application/configuration.rb @@ -110,7 +110,7 @@ module Rails def colorize_logging=(val) @colorize_logging = val - Rails::LogSubscriber.colorize_logging = val + ActiveSupport::LogSubscriber.colorize_logging = val self.generators.colorize_logging = val end diff --git a/railties/lib/rails/log_subscriber.rb b/railties/lib/rails/log_subscriber.rb deleted file mode 100644 index a30701d4d5..0000000000 --- a/railties/lib/rails/log_subscriber.rb +++ /dev/null @@ -1,115 +0,0 @@ -require 'active_support/core_ext/class/inheritable_attributes' -require 'active_support/notifications' - -module Rails - # Rails::LogSubscriber is an object set to consume ActiveSupport::Notifications - # on initialization with solely purpose of logging. The log subscriber dispatches - # notifications to a regirested object based on its given namespace. - # - # An example would be Active Record log subscriber responsible for logging queries: - # - # module ActiveRecord - # class Railtie - # class LogSubscriber < Rails::LogSubscriber - # def sql(event) - # "#{event.payload[:name]} (#{event.duration}) #{event.payload[:sql]}" - # end - # end - # end - # end - # - # It's finally registed as: - # - # Rails::LogSubscriber.add :active_record, ActiveRecord::Railtie::LogSubscriber.new - # - # So whenever a "sql.active_record" notification arrive to Rails::LogSubscriber, - # it will properly dispatch the event (ActiveSupport::Notifications::Event) to - # the sql method. - # - # This is useful because it avoids spanning several log subscribers just for logging - # purposes(which slows down the main thread). Besides of providing a centralized - # facility on top of Rails.logger. - # - # Log subscriber also has some helpers to deal with logging and automatically flushes - # all logs when the request finishes (via action_dispatch.callback notification). - class LogSubscriber - mattr_accessor :colorize_logging - self.colorize_logging = true - - # Embed in a String to clear all previous ANSI sequences. - CLEAR = "\e[0m" - BOLD = "\e[1m" - - # Colors - BLACK = "\e[30m" - RED = "\e[31m" - GREEN = "\e[32m" - YELLOW = "\e[33m" - BLUE = "\e[34m" - MAGENTA = "\e[35m" - CYAN = "\e[36m" - WHITE = "\e[37m" - - def self.add(namespace, log_subscriber, notifier = ActiveSupport::Notifications) - log_subscribers << log_subscriber - @flushable_loggers = nil - - log_subscriber.public_methods(false).each do |event| - notifier.subscribe("#{event}.#{namespace}") do |*args| - next if log_subscriber.logger.nil? - - begin - log_subscriber.send(event, ActiveSupport::Notifications::Event.new(*args)) - rescue Exception => e - Rails.logger.error "Could not log #{args[0].inspect} event. #{e.class}: #{e.message}" - end - end - end - end - - def self.log_subscribers - @log_subscribers ||= [] - end - - def self.flushable_loggers - @flushable_loggers ||= begin - loggers = log_subscribers.map(&:logger) - loggers.uniq! - loggers.select { |l| l.respond_to?(:flush) } - end - end - - # Flush all log_subscribers' logger. - def self.flush_all! - flushable_loggers.each(&:flush) - end - - # By default, we use the Rails.logger for logging. - def logger - Rails.logger - end - - protected - - %w(info debug warn error fatal unknown).each do |level| - class_eval <<-METHOD, __FILE__, __LINE__ + 1 - def #{level}(*args, &block) - return unless logger - logger.#{level}(*args, &block) - end - METHOD - end - - # Set color by using a string or one of the defined constants. If a third - # option is set to true, it also adds bold to the string. This is based - # on Highline implementation and it automatically appends CLEAR to the end - # of the returned String. - # - def color(text, color, bold=false) - return text unless colorize_logging - color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol) - bold = bold ? BOLD : "" - "#{bold}#{color}#{text}#{CLEAR}" - end - end -end diff --git a/railties/lib/rails/log_subscriber/test_helper.rb b/railties/lib/rails/log_subscriber/test_helper.rb deleted file mode 100644 index 9b7b0738cd..0000000000 --- a/railties/lib/rails/log_subscriber/test_helper.rb +++ /dev/null @@ -1,97 +0,0 @@ -require 'rails/log_subscriber' - -module Rails - class LogSubscriber - # Provides some helpers to deal with testing log subscribers by setting up - # notifications. Take for instance Active Record subscriber tests: - # - # class SyncLogSubscriberTest < ActiveSupport::TestCase - # include Rails::LogSubscriber::TestHelper - # Rails::LogSubscriber.add(:active_record, ActiveRecord::Railties::LogSubscriber.new) - # - # def test_basic_query_logging - # Developer.all - # wait - # assert_equal 1, @logger.logged(:debug).size - # assert_match /Developer Load/, @logger.logged(:debug).last - # assert_match /SELECT \* FROM "developers"/, @logger.logged(:debug).last - # end - # - # class SyncLogSubscriberTest < ActiveSupport::TestCase - # include Rails::LogSubscriber::SyncTestHelper - # include LogSubscriberTest - # end - # - # class AsyncLogSubscriberTest < ActiveSupport::TestCase - # include Rails::LogSubscriber::AsyncTestHelper - # include LogSubscriberTest - # end - # end - # - # All you need to do is to ensure that your log subscriber is added to Rails::Subscriber, - # as in the second line of the code above. The test helpers is reponsible for setting - # up the queue, subscriptions and turning colors in logs off. - # - # The messages are available in the @logger instance, which is a logger with limited - # powers (it actually do not send anything to your output), and you can collect them - # doing @logger.logged(level), where level is the level used in logging, like info, - # debug, warn and so on. - # - module TestHelper - def setup - @logger = MockLogger.new - @notifier = ActiveSupport::Notifications::Notifier.new(queue) - - Rails::LogSubscriber.colorize_logging = false - - set_logger(@logger) - ActiveSupport::Notifications.notifier = @notifier - end - - def teardown - set_logger(nil) - ActiveSupport::Notifications.notifier = nil - end - - class MockLogger - attr_reader :flush_count - - def initialize - @flush_count = 0 - @logged = Hash.new { |h,k| h[k] = [] } - end - - def method_missing(level, message) - @logged[level] << message - end - - def logged(level) - @logged[level].compact.map { |l| l.to_s.strip } - end - - def flush - @flush_count += 1 - end - end - - # Wait notifications to be published. - def wait - @notifier.wait - end - - # Overwrite if you use another logger in your log subscriber: - # - # def logger - # ActiveRecord::Base.logger = @logger - # end - # - def set_logger(logger) - Rails.logger = logger - end - - def queue - ActiveSupport::Notifications::Fanout.new - end - end - end -end \ No newline at end of file diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb index 73e9af3b41..b3dc1f894c 100644 --- a/railties/lib/rails/rack/logger.rb +++ b/railties/lib/rails/rack/logger.rb @@ -1,10 +1,9 @@ -require 'rails/log_subscriber' require 'active_support/core_ext/time/conversions' module Rails module Rack # Log the request started and flush all loggers after it. - class Logger < Rails::LogSubscriber + class Logger < ActiveSupport::LogSubscriber def initialize(app) @app = app end @@ -16,20 +15,19 @@ module Rails after_dispatch(env) end - protected + protected - def before_dispatch(env) - request = ActionDispatch::Request.new(env) - path = request.fullpath + def before_dispatch(env) + request = ActionDispatch::Request.new(env) + path = request.fullpath - info "\n\nStarted #{env["REQUEST_METHOD"]} \"#{path}\" " \ - "for #{request.ip} at #{Time.now.to_default_s}" - end - - def after_dispatch(env) - Rails::LogSubscriber.flush_all! - end + info "\n\nStarted #{env["REQUEST_METHOD"]} \"#{path}\" " \ + "for #{request.ip} at #{Time.now.to_default_s}" + end + def after_dispatch(env) + ActiveSupport::LogSubscriber.flush_all! + end end end end diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb index ad776933f2..dbdbfea509 100644 --- a/railties/lib/rails/railtie.rb +++ b/railties/lib/rails/railtie.rb @@ -114,36 +114,6 @@ module Rails # end # end # - # == Adding your subscriber - # - # Since version 3.0, Rails ships with a notification system which is used for several - # purposes, including logging. If you are sending notifications in your Railtie, you may - # want to add a subscriber to consume such notifications for logging purposes. - # - # The subscriber is added under the railtie_name namespace and only consumes notifications - # under the given namespace. For example, let's suppose your railtie is publishing the - # following "something_expensive" instrumentation: - # - # ActiveSupport::Notifications.instrument "my_railtie.something_expensive" do - # # something expensive - # end - # - # You can log this instrumentation with your own Rails::Subscriber: - # - # class MyRailtie::Subscriber < Rails::Subscriber - # def something_expensive(event) - # info("Something expensive took %.1fms" % event.duration) - # end - # end - # - # By registering it: - # - # class MyRailtie < Railtie - # subscriber :my_gem, MyRailtie::Subscriber.new - # end - # - # Take a look in Rails::Subscriber docs for more information. - # # == Application, Plugin and Engine # # A Rails::Engine is nothing more than a Railtie with some initializers already set. @@ -176,8 +146,8 @@ module Rails ActiveSupport::Deprecation.warn "railtie_name is deprecated and has no effect", caller end - def log_subscriber(name, log_subscriber) - Rails::LogSubscriber.add(name, log_subscriber) + def log_subscriber(*) + ActiveSupport::Deprecation.warn "log_subscriber is deprecated and has no effect", caller end def rake_tasks(&blk) diff --git a/railties/test/log_subscriber_test.rb b/railties/test/log_subscriber_test.rb deleted file mode 100644 index a3a755ae62..0000000000 --- a/railties/test/log_subscriber_test.rb +++ /dev/null @@ -1,123 +0,0 @@ -require 'abstract_unit' -require 'rails/log_subscriber/test_helper' - -class MyLogSubscriber < Rails::LogSubscriber - attr_reader :event - - def some_event(event) - @event = event - info event.name - end - - def foo(event) - debug "debug" - info "info" - warn "warn" - end - - def bar(event) - info "#{color("cool", :red)}, #{color("isn't it?", :blue, true)}" - end - - def puke(event) - raise "puke" - end -end - -class SyncLogSubscriberTest < ActiveSupport::TestCase - include Rails::LogSubscriber::TestHelper - - def setup - super - @log_subscriber = MyLogSubscriber.new - end - - def teardown - super - Rails::LogSubscriber.log_subscribers.clear - end - - def instrument(*args, &block) - ActiveSupport::Notifications.instrument(*args, &block) - end - - def test_proxies_method_to_rails_logger - @log_subscriber.foo(nil) - assert_equal %w(debug), @logger.logged(:debug) - assert_equal %w(info), @logger.logged(:info) - assert_equal %w(warn), @logger.logged(:warn) - end - - def test_set_color_for_messages - Rails::LogSubscriber.colorize_logging = true - @log_subscriber.bar(nil) - assert_equal "\e[31mcool\e[0m, \e[1m\e[34misn't it?\e[0m", @logger.logged(:info).last - end - - def test_does_not_set_color_if_colorize_logging_is_set_to_false - @log_subscriber.bar(nil) - assert_equal "cool, isn't it?", @logger.logged(:info).last - end - - def test_event_is_sent_to_the_registered_class - Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber - instrument "some_event.my_log_subscriber" - wait - assert_equal %w(some_event.my_log_subscriber), @logger.logged(:info) - end - - def test_event_is_an_active_support_notifications_event - Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber - instrument "some_event.my_log_subscriber" - wait - assert_kind_of ActiveSupport::Notifications::Event, @log_subscriber.event - end - - def test_does_not_send_the_event_if_it_doesnt_match_the_class - Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber - instrument "unknown_event.my_log_subscriber" - wait - # If we get here, it means that NoMethodError was not raised. - end - - def test_does_not_send_the_event_if_logger_is_nil - Rails.logger = nil - @log_subscriber.expects(:some_event).never - Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber - instrument "some_event.my_log_subscriber" - wait - end - - def test_does_not_fail_with_non_namespaced_events - Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber - instrument "whatever" - wait - end - - def test_flushes_loggers - Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber - Rails::LogSubscriber.flush_all! - assert_equal 1, @logger.flush_count - end - - def test_flushes_the_same_logger_just_once - Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber - Rails::LogSubscriber.add :another, @log_subscriber - Rails::LogSubscriber.flush_all! - wait - assert_equal 1, @logger.flush_count - end - - def test_logging_does_not_die_on_failures - Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber - instrument "puke.my_log_subscriber" - instrument "some_event.my_log_subscriber" - wait - - assert_equal 1, @logger.logged(:info).size - assert_equal 'some_event.my_log_subscriber', @logger.logged(:info).last - - assert_equal 1, @logger.logged(:error).size - assert_equal 'Could not log "puke.my_log_subscriber" event. RuntimeError: puke', @logger.logged(:error).last - end -end \ No newline at end of file -- cgit v1.2.3