summaryrefslogtreecommitdiff
path: root/lib/gitlab/exception_log_formatter.rb
blob: 52ad67d6f8bb4e672ef6591c0706bf0e4a06c84a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# frozen_string_literal: true

module Gitlab
  module ExceptionLogFormatter
    class << self
      def format!(exception, payload)
        return unless exception

        # Elasticsearch/Fluentd don't handle nested structures well.
        # Use periods to flatten the fields.
        payload.merge!(
          'exception.class' => exception.class.name,
          'exception.message' => sanitize_message(exception)
        )

        if exception.backtrace
          payload['exception.backtrace'] = Rails.backtrace_cleaner.clean(exception.backtrace)
        end

        if exception.cause
          payload['exception.cause_class'] = exception.cause.class.name
        end

        if sql = find_sql(exception)
          payload['exception.sql'] = sql
        end
      end

      def find_sql(exception)
        if exception.is_a?(ActiveRecord::StatementInvalid)
          # StatementInvalid may be caused by a statement timeout or a bad query
          normalize_query(exception.sql.to_s)
        elsif exception.cause.present?
          find_sql(exception.cause)
        end
      end

      private

      def normalize_query(sql)
        PgQuery.normalize(sql)
      rescue PgQuery::ParseError
        sql
      end

      def sanitize_message(exception)
        Gitlab::Sanitizers::ExceptionMessage.clean(exception.class.name, exception.message)
      end
    end
  end
end