You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.7 KiB

10 months ago
10 months ago
10 months ago
  1. module SemanticLogger
  2. class Base
  3. # Log message at the specified level
  4. def log_internal(level, index, message = nil, payload = nil, exception = nil)
  5. # Handle variable number of arguments by detecting exception object and payload hash.
  6. if exception.nil? && payload.nil? && message.respond_to?(:backtrace) && message.respond_to?(:message)
  7. exception = message
  8. message = nil
  9. elsif exception.nil? && payload && payload.respond_to?(:backtrace) && payload.respond_to?(:message)
  10. exception = payload
  11. payload = nil
  12. elsif message && !message.is_a?(String)
  13. payload = message
  14. message = 'payload is'
  15. end
  16. log = Log.new(name, level, index)
  17. should_log =
  18. if exception.nil? && payload.nil? && message.is_a?(Hash)
  19. # All arguments as a hash in the message.
  20. log.assign(**log.extract_arguments(message))
  21. elsif exception.nil? && message && payload && payload.is_a?(Hash)
  22. # Message supplied along with a hash with the remaining arguments.
  23. log.assign(**log.extract_arguments(payload, message))
  24. else
  25. # All fields supplied directly.
  26. log.assign(message:, payload:, exception:)
  27. end
  28. # Add result of block to message or payload if not nil
  29. if block_given?
  30. result = yield(log)
  31. if result.is_a?(String)
  32. log.message = log.message.nil? ? result : "#{log.message} -- #{result}"
  33. elsif result.is_a?(Hash)
  34. log.assign_hash(result)
  35. end
  36. end
  37. # Log level may change during assign due to :on_exception_level
  38. self.log(log) if should_log && should_log?(log)
  39. end
  40. end
  41. end