From 3246f38328f20a106d0f720c6a4ff76eca1c6a3f Mon Sep 17 00:00:00 2001 From: Michael Chui Date: Tue, 20 Aug 2024 15:24:29 -0700 Subject: [PATCH] Guarantee level_override exists Some Ruby apps subclass Logger without running the superclass constructor, which means that `@level_override` isn't initialized properly. This can be fixed in some cases, but the gem should maintain backwards compatibility. --- lib/logger.rb | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/lib/logger.rb b/lib/logger.rb index a1f48d4..4735209 100644 --- a/lib/logger.rb +++ b/lib/logger.rb @@ -381,7 +381,7 @@ class Logger # Logging severity threshold (e.g. Logger::INFO). def level - @level_override[Fiber.current] || @level + level_override[Fiber.current] || @level end # Sets the log level; returns +severity+. @@ -406,14 +406,14 @@ def level=(severity) # logger.debug { "Hello" } # end def with_level(severity) - prev, @level_override[Fiber.current] = level, Severity.coerce(severity) + prev, level_override[Fiber.current] = level, Severity.coerce(severity) begin yield ensure if prev - @level_override[Fiber.current] = prev + level_override[Fiber.current] = prev else - @level_override.delete(Fiber.current) + level_override.delete(Fiber.current) end end end @@ -746,6 +746,11 @@ def format_severity(severity) SEV_LABEL[severity] || 'ANY' end + # Guarantee the existence of this ivar even when subclasses don't call the superclass constructor. + def level_override + @level_override ||= {} + end + def format_message(severity, datetime, progname, msg) (@formatter || @default_formatter).call(severity, datetime, progname, msg) end