From d42b3d4347547b7790d0a716e7548baccf408076 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 20 Jan 2012 11:45:29 -0800 Subject: [PATCH] add a broadcasting logger so we can split logs --- activesupport/lib/active_support/logger.rb | 23 +++++++++ activesupport/test/broadcast_logger_test.rb | 57 +++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 activesupport/test/broadcast_logger_test.rb diff --git a/activesupport/lib/active_support/logger.rb b/activesupport/lib/active_support/logger.rb index 66e8fcadb4..8288368d8d 100644 --- a/activesupport/lib/active_support/logger.rb +++ b/activesupport/lib/active_support/logger.rb @@ -1,6 +1,29 @@ require 'logger' module ActiveSupport + # Broadcasts logs to multiple loggers + class BroadcastLogger < ::Logger # :nodoc: + attr_reader :logs + + def initialize(logs) + super(nil) + @logs = logs + end + + def add(severity, message = nil, progname = nil, &block) + super + logs.each { |l| l.add(severity, message, progname, &block) } + end + + def <<(x) + logs.each { |l| l << x } + end + + def close + logs.each(&:close) + end + end + class Logger < ::Logger def initialize(*args) super diff --git a/activesupport/test/broadcast_logger_test.rb b/activesupport/test/broadcast_logger_test.rb new file mode 100644 index 0000000000..af34221cfe --- /dev/null +++ b/activesupport/test/broadcast_logger_test.rb @@ -0,0 +1,57 @@ +require 'abstract_unit' + +module ActiveSupport + class BroadcastLoggerTest < TestCase + def test_debug + log1 = FakeLogger.new + log2 = FakeLogger.new + + logger = BroadcastLogger.new [log1, log2] + logger.debug "foo" + assert_equal 'foo', log1.adds.first[2] + assert_equal 'foo', log2.adds.first[2] + end + + def test_close + log1 = FakeLogger.new + log2 = FakeLogger.new + + logger = BroadcastLogger.new [log1, log2] + logger.close + assert log1.closed, 'should be closed' + assert log2.closed, 'should be closed' + end + + def test_chevrons + log1 = FakeLogger.new + log2 = FakeLogger.new + + logger = BroadcastLogger.new [log1, log2] + logger << "foo" + assert_equal %w{ foo }, log1.chevrons + assert_equal %w{ foo }, log2.chevrons + end + + class FakeLogger + attr_reader :adds, :closed, :chevrons + + def initialize + @adds = [] + @closed = false + @chevrons = [] + end + + def << x + @chevrons << x + end + + def add(*args) + @adds << args + end + + def close + @closed = true + end + end + end +end