Skip to content

Commit

Permalink
Add support for kwargs when delegating calls to custom loggers
Browse files Browse the repository at this point in the history
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)`
  • Loading branch information
jenshenny committed Oct 10, 2023
1 parent c7e3cf2 commit 6070685
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
8 changes: 4 additions & 4 deletions activesupport/lib/active_support/broadcast_logger.rb
Expand Up @@ -223,15 +223,15 @@ def dispatch(&block)
@broadcasts.each { |logger| block.call(logger) }
end

def method_missing(name, *args, &block)
def method_missing(name, *args, **kwargs, &block)
loggers = @broadcasts.select { |logger| logger.respond_to?(name) }

if loggers.none?
super(name, *args, &block)
super(name, *args, **kwargs, &block)
elsif loggers.one?
loggers.first.send(name, *args, &block)
loggers.first.send(name, *args, **kwargs, &block)
else
loggers.map { |logger| logger.send(name, *args, &block) }
loggers.map { |logger| logger.send(name, *args, **kwargs, &block) }
end
end

Expand Down
20 changes: 20 additions & 0 deletions activesupport/test/broadcast_logger_test.rb
Expand Up @@ -278,6 +278,18 @@ def info(msg, &block)
assert(called)
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
attr_reader :adds, :closed, :chevrons
attr_accessor :level, :progname, :formatter, :local_level
Expand All @@ -300,6 +312,14 @@ def bar
yield
end

def baz(param)
true
end

def qux(param:)
true
end

def debug(message, &block)
add(::Logger::DEBUG, message, &block)
end
Expand Down

0 comments on commit 6070685

Please sign in to comment.