Module: Carbonyte::Initializers::Lograge

Extended by:
ActiveSupport::Concern
Included in:
Engine
Defined in:
lib/carbonyte/initializers/lograge.rb

Overview

This initializer setups lograge and automatically logs exceptions

Constant Summary collapse

PARAMS_EXCEPTIONS =

Items to be removed from ‘params` hash

%w[controller action].freeze
LOG_TYPE =

Log type, this allows to distinguish these logs from others

'SERVER_REQUEST'

Instance Method Summary collapse

Instance Method Details

#add_rescued_exception(opts, exc) ⇒ Object

Adds the rescued exception (if any) to the Lograge event



48
49
50
51
52
53
54
55
56
# File 'lib/carbonyte/initializers/lograge.rb', line 48

def add_rescued_exception(opts, exc)
  return unless exc

  opts[:rescued_exception] = {
    name: exc.class.name,
    message: exc.message,
    backtrace: %('#{Array(exc.backtrace.first(10)).join("\n\t")}')
  }
end

#custom_options(event) ⇒ Object

Adds custom options to the Lograge event



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/carbonyte/initializers/lograge.rb', line 35

def custom_options(event)
  opts = {
    type: LOG_TYPE,
    params: event.payload[:params].except(*PARAMS_EXCEPTIONS),
    correlation_id: RequestStore.store[:correlation_id],
    environment: Rails.env,
    pid: ::Process.pid
  }
  add_rescued_exception(opts, RequestStore.store[:rescued_exception])
  opts
end

#custom_payload(controller) ⇒ Object

Adds custom payload to the Lograge event



59
60
61
62
63
64
65
66
# File 'lib/carbonyte/initializers/lograge.rb', line 59

def custom_payload(controller)
  payload = {
    headers: parse_headers(controller.request.headers),
    remote_ip: controller.remote_ip
  }
  payload[:user_id] = controller.current_user&.id if controller.respond_to?(:current_user)
  payload
end

#parse_headers(headers) ⇒ Object

Parses headers returning only those starting with “HTTP”, but excluding cookies



69
70
71
# File 'lib/carbonyte/initializers/lograge.rb', line 69

def parse_headers(headers)
  headers.to_h.select { |k, _v| k.start_with?('HTTP') and k != 'HTTP_COOKIE' }
end