Permalink
Browse files

Add logger.push_tags and .pop_tags to complement logger.tagged

  • Loading branch information...
1 parent d1cbcd7 commit d36f57f430c011e889c7d45335beea4ea0dc9769 @jeremy jeremy committed Sep 26, 2012
View
@@ -1,5 +1,19 @@
## Rails 4.0.0 (unreleased) ##
+* Add logger.push_tags and .pop_tags to complement logger.tagged:
+
+ class Job
+ def before
+ Rails.logger.push_tags :jobs, self.class.name
+ end
+
+ def after
+ Rails.logger.pop_tags 2
+ end
+ end
+
+ *Jeremy Kemper*
+
* Allow delegation to the class using the `:class` keyword, replacing
`self.class` usage:
@@ -20,7 +20,24 @@ def call(severity, timestamp, progname, msg)
super(severity, timestamp, progname, "#{tags_text}#{msg}")
end
- def clear!
+ def tagged(*tags)
+ new_tags = push_tags *tags
+ yield self
+ ensure
+ pop_tags new_tags.size
+ end
+
+ def push_tags(*tags)
+ tags.flatten.reject(&:blank?).tap do |new_tags|
+ current_tags.concat new_tags
+ end
+ end
+
+ def pop_tags(size = 1)
+ current_tags.pop size
+ end
+
+ def clear_tags!
current_tags.clear
end
@@ -29,30 +46,27 @@ def current_tags
end
private
- def tags_text
- tags = current_tags
- if tags.any?
- tags.collect { |tag| "[#{tag}] " }.join
+ def tags_text
+ tags = current_tags
+ if tags.any?
+ tags.collect { |tag| "[#{tag}] " }.join
+ end
end
- end
end
def self.new(logger)
logger.formatter.extend Formatter
logger.extend(self)
end
- def tagged(*new_tags)
- tags = formatter.current_tags
- new_tags = new_tags.flatten.reject(&:blank?)
- tags.concat new_tags
- yield self
- ensure
- tags.pop(new_tags.size)
+ delegate :push_tags, :pop_tags, :clear_tags!, to: :formatter
+
+ def tagged(*tags)
+ formatter.tagged(*tags) { yield self }
end
def flush
- formatter.clear!
+ clear_tags!
super if defined?(super)
end
end
@@ -29,6 +29,23 @@ def flush(*)
assert_equal "[BCX] [Jason] [New] Funky time\n", @output.string
end
+ test "tagged are flattened" do
+ @logger.tagged("BCX", %w(Jason New)) { @logger.info "Funky time" }
+ assert_equal "[BCX] [Jason] [New] Funky time\n", @output.string
+ end
+
+ test "push and pop tags directly" do
+ assert_equal %w(A B C), @logger.push_tags('A', ['B', ' ', ['C']])
+ @logger.info 'a'
+ assert_equal %w(C), @logger.pop_tags
+ @logger.info 'b'
+ assert_equal %w(B), @logger.pop_tags(1)
+ @logger.info 'c'
+ assert_equal [], @logger.clear_tags!
+ @logger.info 'd'
+ assert_equal "[A] [B] [C] a\n[A] [B] b\n[A] c\nd\n", @output.string
+ end
+
test "does not strip message content" do
@logger.info " Hello"
assert_equal " Hello\n", @output.string

0 comments on commit d36f57f

Please sign in to comment.