Class: RuboCop::Cop::Mdsol::LogWithData

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/mdsol/log_with_data.rb

Overview

Favor the logger.<level>_with_data method for structured logging.

Examples:

# bad - string interpolations exceed the threshold (configurable via AllowedStringInterpolations setting)
Rails.logger.info("a message with more than 2 interpolations: #{foo} #{bar} #{baz}")

# bad - string interpolation contains Enumerable methods (:map, :collect)
Rails.logger.info("Deleted the following records: #{records.map(&:id)}")

# good
Rails.logger.info("a message")

# good - string interpolations are within the threshold (configurable via AllowedStringInterpolations setting)
Rails.logger.info("a message with 2 interpolations: #{foo} #{bar}")

# good
Rails.logger.info_with_data("Created the record", record_id: record.id, status: status)

# good
Rails.logger.info_with_data("Deleted the following records", record_ids: results.records.map(&:id))

Constant Summary collapse

MSG =
"Use `logger.%<method>s_with_data(msg, data_hash)` instead. See https://github.com/mdsol/astinus#using-context-data-logging"
RESTRICT_ON_SEND =
%i[logger debug info warn error].freeze
FORBIDDEN_ENUMERABLE_METHODS =
%i[map collect].freeze
DEFAULT_STRING_INTERPOLATION_THRESHOLD =
2

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



48
49
50
51
52
53
54
55
56
57
# File 'lib/rubocop/cop/mdsol/log_with_data.rb', line 48

def on_send(node)
  logger_with_interpolation(node) do |logger_owner, log_method, log_message|
    return unless registered_logger_owners.include?(logger_owner.to_s)

    if interpoloations_exceed_threshold?(log_message) || contain_forbidden_enumerable_method?(log_message)
      msg = format(MSG, method: log_method.to_s)
      add_offense(node, message: msg)
    end
  end
end