Module: Belt::Helpers::ErrorLogging

Defined in:
lib/belt/helpers/error_logging.rb

Class Method Summary collapse

Class Method Details

.filter_backtrace(backtrace) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/belt/helpers/error_logging.rb', line 32

def filter_backtrace(backtrace)
  return [] if backtrace.nil? || backtrace.empty?

  app_patterns = [%r{/var/task/}, %r{lambda/}, %r{controllers/}, %r{models/}, %r{lib/}, %r{helpers/}]
  exclude_patterns = [%r{/var/runtime/}, %r{/opt/ruby/}, %r{/gems/}, /rubygems/, /<internal:/]

  app_lines = []
  lib_lines = []

  backtrace.each do |line|
    next if exclude_patterns.any? { |pattern| line.match?(pattern) }

    if app_patterns.any? { |pattern| line.match?(pattern) }
      app_lines << line
    else
      lib_lines << line
    end
  end

  (app_lines.first(10) + lib_lines.first(3)).compact
end

.log_error(logger, message, error, context = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/belt/helpers/error_logging.rb', line 8

def log_error(logger, message, error, context = {})
  filtered_backtrace = filter_backtrace(error.backtrace || [])

  if logger
    logger.error(message,
                 error_class: error.class.name,
                 error_message: error.message,
                 backtrace: filtered_backtrace,
                 backtrace_full: error.backtrace&.first(20),
                 **context)
  else
    require 'json'
    puts JSON.generate({
                         level: 'ERROR',
                         message: message,
                         error_class: error.class.name,
                         error_message: error.message,
                         backtrace: filtered_backtrace,
                         timestamp: Time.now.utc.iso8601,
                         **context
                       })
  end
end