reidmorrison / semantic_logger

Semantic Logger is a feature rich logging framework, and replacement for existing Ruby & Rails loggers.
https://logger.rocketjob.io/
Apache License 2.0
873 stars 124 forks source link

Exception on `logger.error({ payload: '', foo: 'bar' })` (trying to log an arbitrary hash with `payload` key) #250

Closed Drowze closed 1 year ago

Drowze commented 2 years ago

Environment

Expected Behavior

I'd expect SemanticLogger to be fully compatible with ::Logger, so I'd expect no error to be raised. Perhaps detecting it's an arbitrary hash and considering it as a message (i.e. treat it the same as logger.error(message: { payload: '', foo: 'bar' }) and maybe also raise a warning pointing to bad use of payload keyword) would be a good choice.

Actual Behavior

Logger.new($stdout).error({payload: '', foo: 'bar'})
# E, [2022-11-17T21:51:37.400739 #74531] ERROR -- : {:payload=>"", :foo=>"bar"}

require 'semantic_logger'
SemanticLogger.add_appender(io: $stdout)
SemanticLogger['a'].error({ payload: '', foo: 'bar' })
# exception raised...

stacktrace:

/Users/Drowze/.asdf/installs/ruby/3.1.2/lib/ruby/gems/3.1.0/gems/semantic_logger-4.12.0/lib/semantic_logger/log.rb:77:in `assign': unknown keyword: :foo (ArgumentError)
        from /Users/Drowze/.asdf/installs/ruby/3.1.2/lib/ruby/gems/3.1.0/gems/semantic_logger-4.12.0/lib/semantic_logger/base.rb:333:in `log_internal'
        from /Users/Drowze/.asdf/installs/ruby/3.1.2/lib/ruby/gems/3.1.0/gems/semantic_logger-4.12.0/lib/semantic_logger/concerns/compatibility.rb:44:in `add'
        from /Users/Drowze/.asdf/installs/ruby/3.1.2/lib/ruby/gems/3.1.0/gems/semantic_logger-4.12.0/lib/semantic_logger/logger.rb:71:in `log'
        from (irb):12:in `<main>'
        from /Users/Drowze/.asdf/installs/ruby/3.1.2/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
        from /Users/Drowze/.asdf/installs/ruby/3.1.2/bin/irb:25:in `load'
        from /Users/Drowze/.asdf/installs/ruby/3.1.2/bin/irb:25:in `<main>'

Note: this happened on a real codebase when I was installing rails_semantic_logger in our project. I had a change similar to the following to fix it:

      Rails.logger.info(
-       message: "#{self.class.name}##{method}",
-       payload: message.payload,
-       headers: message.headers.except(:key)
+       "#{self.class.name}##{method}",
+       payload: {
+         payload: message.payload,
+         headers: message.headers.except(:key)
+       }
      )
reidmorrison commented 1 year ago

Correct, payload is a reserved keyword for Semantic Logger and must be a Hash. Strings are not permitted.