From 0ab89d8e36ba58a95244b4c6dd49d53fac7a699f Mon Sep 17 00:00:00 2001 From: Mayra Cabrera Date: Wed, 10 Jul 2019 19:26:47 +0000 Subject: Add a rubocop for Rails.logger Suggests to use a JSON structured log instead Related to https://gitlab.com/gitlab-org/gitlab-ce/issues/54102 --- rubocop/cop/gitlab/rails_logger.rb | 51 ++++++++++++++++++++++++++++++++++++++ rubocop/rubocop.rb | 1 + 2 files changed, 52 insertions(+) create mode 100644 rubocop/cop/gitlab/rails_logger.rb (limited to 'rubocop') diff --git a/rubocop/cop/gitlab/rails_logger.rb b/rubocop/cop/gitlab/rails_logger.rb new file mode 100644 index 00000000000..d1a06a9a100 --- /dev/null +++ b/rubocop/cop/gitlab/rails_logger.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +require_relative '../../code_reuse_helpers' + +module RuboCop + module Cop + module Gitlab + class RailsLogger < ::RuboCop::Cop::Cop + include CodeReuseHelpers + + # This cop checks for the Rails.logger in the codebase + # + # @example + # + # # bad + # Rails.logger.error("Project #{project.full_path} could not be saved") + # + # # good + # Gitlab::AppLogger.error("Project %{project_path} could not be saved" % { project_path: project.full_path }) + MSG = 'Use a structured JSON logger instead of `Rails.logger`. ' \ + 'https://docs.gitlab.com/ee/development/logging.html'.freeze + + def_node_matcher :rails_logger?, <<~PATTERN + (send (const nil? :Rails) :logger ... ) + PATTERN + + WHITELISTED_DIRECTORIES = %w[ + spec + ].freeze + + def on_send(node) + return if in_whitelisted_directory?(node) + return unless rails_logger?(node) + + add_offense(node, location: :expression) + end + + def in_whitelisted_directory?(node) + path = file_path_for_node(node) + + WHITELISTED_DIRECTORIES.any? do |directory| + path.start_with?( + File.join(rails_root, directory), + File.join(rails_root, 'ee', directory) + ) + end + end + end + end + end +end diff --git a/rubocop/rubocop.rb b/rubocop/rubocop.rb index 27c63d92ae5..ba61a634d97 100644 --- a/rubocop/rubocop.rb +++ b/rubocop/rubocop.rb @@ -3,6 +3,7 @@ require_relative 'cop/gitlab/predicate_memoization' require_relative 'cop/gitlab/httparty' require_relative 'cop/gitlab/finder_with_find_by' require_relative 'cop/gitlab/union' +require_relative 'cop/gitlab/rails_logger' require_relative 'cop/include_action_view_context' require_relative 'cop/include_sidekiq_worker' require_relative 'cop/safe_params' -- cgit v1.2.1