diff --git a/lib/semantic_logger/base.rb b/lib/semantic_logger/base.rb index 8fa26a0..155e692 100644 --- a/lib/semantic_logger/base.rb +++ b/lib/semantic_logger/base.rb @@ -211,7 +211,15 @@ def tags end def named_tags - SemanticLogger.named_tags + SemanticLogger.named_tags.merge(@named_tags || {}) + end + + # Sets named tags which are local to the logger instance. + # + # Local named tags are merged into the log entry along with the thread-level ones + # and those set via `#tagged` or `#with_tags`. + def named_tags=(tags) + (@named_tags ||= {}).merge!(tags) end # Returns the list of tags pushed after flattening them out and removing blanks @@ -327,6 +335,10 @@ def log_internal(level, index, message = nil, payload = nil, exception = nil) end log = Log.new(name, level, index) + + # Apply the named tags to the log entry + log.named_tags = named_tags + should_log = if exception.nil? && payload.nil? && message.is_a?(Hash) # All arguments as a hash in the message. diff --git a/test/logger_test.rb b/test/logger_test.rb index 8c6e224..06701f5 100644 --- a/test/logger_test.rb +++ b/test/logger_test.rb @@ -50,6 +50,14 @@ def self.call(log) end end + describe "#named_tags=" do + it "adds local named tags to logger" do + logger.named_tags = {test: "123"} + assert_equal({test: "123"}, logger.named_tags) + assert_equal({}, SemanticLogger.named_tags) + end + end + describe "Compatibility" do # Ensure that any log level can be logged Logger::Severity.constants.each do |level| @@ -152,6 +160,54 @@ def self.call(log) assert_equal logger.object_id, yielded_logger.object_id end end + + it "adds logger-local named tags to log entries" do + logger.named_tags = {test: "123"} + + logger.tagged do + logger.info("test") + end + + assert log = logger.events.first + assert_equal({test: "123"}, log.named_tags) + end + + it "does not change local tags" do + logger.named_tags = {test: "123"} + + logger.tagged(foo: "bar") do + logger.info("test") + end + + assert_equal({test: "123"}, logger.named_tags) + assert_equal({}, SemanticLogger.named_tags) + assert_equal({test: "123", foo: "bar"}, logger.events.first.named_tags) + end + + it "does not override global tags" do + SemanticLogger.push_named_tags(global: true) + logger.named_tags = {test: "123"} + + logger.info("test") + + assert_equal({global: true, test: "123"}, logger.events.first.named_tags) + assert_equal({global: true}, SemanticLogger.named_tags) + + SemanticLogger.pop_named_tags + end + + it "does no add local named tags to other loggers in block" do + another_logger = SemanticLogger::Test::CaptureLogEvents.new + logger.named_tags = {test: "123"} + + logger.tagged(foo: "bar") do + logger.info("has local tags") + another_logger.info("does not have local tags") + end + + assert_equal({test: "123", foo: "bar"}, logger.events.first.named_tags) + assert_equal({foo: "bar"}, another_logger.events.first.named_tags) + end end end end