Skip to content

Commit

Permalink
Guarantee level_override exists
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
saraid committed Aug 20, 2024
1 parent 436a7d6 commit 3246f38
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions lib/logger.rb
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ class Logger

# Logging severity threshold (e.g. <tt>Logger::INFO</tt>).
def level
@level_override[Fiber.current] || @level
level_override[Fiber.current] || @level
end

# Sets the log level; returns +severity+.
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 3246f38

Please sign in to comment.