Add support for kwargs when delegating calls to custom loggers

Currently, when a method is called on Rails.logger, the BroadcastLogger will find the loggers that will respond to that method. However, when the method has keyword arguments, they are passed as regular arguments and will throw an ArgumentError. This adds keyword argument support by double splatting hash args.

```
class CustomLogger
  def foo(bar:)
    true
  end
end

Rails.logger.foo(bar: "baz")
```

Expected: `true`

Actual: `wrong number of arguments (given 1, expected 0) (ArgumentError)`
This commit is contained in:
Jenny Shen 2023-10-10 21:43:13 +01:00
parent c7e3cf2561
commit 6070685cf9
No known key found for this signature in database
GPG Key ID: 9C11BD7E024D6ECA
2 changed files with 24 additions and 4 deletions

View File

@ -223,15 +223,15 @@ module ActiveSupport
@broadcasts.each { |logger| block.call(logger) } @broadcasts.each { |logger| block.call(logger) }
end end
def method_missing(name, *args, &block) def method_missing(name, *args, **kwargs, &block)
loggers = @broadcasts.select { |logger| logger.respond_to?(name) } loggers = @broadcasts.select { |logger| logger.respond_to?(name) }
if loggers.none? if loggers.none?
super(name, *args, &block) super(name, *args, **kwargs, &block)
elsif loggers.one? elsif loggers.one?
loggers.first.send(name, *args, &block) loggers.first.send(name, *args, **kwargs, &block)
else else
loggers.map { |logger| logger.send(name, *args, &block) } loggers.map { |logger| logger.send(name, *args, **kwargs, &block) }
end end
end end

View File

@ -278,6 +278,18 @@ module ActiveSupport
assert(called) assert(called)
end end
test "calling a method that accepts args" do
logger = BroadcastLogger.new(CustomLogger.new)
assert(logger.baz("foo"))
end
test "calling a method that accepts kwargs" do
logger = BroadcastLogger.new(CustomLogger.new)
assert(logger.qux(param: "foo"))
end
class CustomLogger class CustomLogger
attr_reader :adds, :closed, :chevrons attr_reader :adds, :closed, :chevrons
attr_accessor :level, :progname, :formatter, :local_level attr_accessor :level, :progname, :formatter, :local_level
@ -300,6 +312,14 @@ module ActiveSupport
yield yield
end end
def baz(param)
true
end
def qux(param:)
true
end
def debug(message, &block) def debug(message, &block)
add(::Logger::DEBUG, message, &block) add(::Logger::DEBUG, message, &block)
end end