Class: Superlogger::SuperloggerMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/superlogger/superlogger_middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ SuperloggerMiddleware

Returns a new instance of SuperloggerMiddleware.



3
4
5
6
7
8
# File 'lib/superlogger/superlogger_middleware.rb', line 3

def initialize(app, options = {})
  @app = app
  @options = {
    include_log_fields: ->(_request) { {} }
  }.merge(options)
end

Instance Method Details

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
# File 'lib/superlogger/superlogger_middleware.rb', line 10

def call(env)
  request = ActionDispatch::Request.new(env)
  
  if request.path.start_with?('/assets/') == false
    process_request(request) { @app.call(env) }
  else
    @app.call(env)
  end
end

#process_request(request) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/superlogger/superlogger_middleware.rb', line 20

def process_request(request)
  setup_request_id_for_logging(request)
  setup_session_id_for_logging(request)

  # Start of request
  Rails.logger.info method: request.method, path: request.fullpath

  t1 = Time.now
  status, _headers, _response = yield
ensure
  t2 = Time.now

  # End of request
  duration = ((t2 - t1) * 1000).to_f.round(2)

  # After the request has been processed, the session ID can change from what it was before the request
  # was processed. As such, we need to setup the session ID again.
  setup_session_id_for_logging(request)

  Rails.logger.info method: request.method, path: request.fullpath, response_time: duration, status: status, **@options[:include_log_fields].call(request)

  [status, _headers, _response]
end

#setup_request_id_for_logging(request) ⇒ Object



44
45
46
# File 'lib/superlogger/superlogger_middleware.rb', line 44

def setup_request_id_for_logging(request)
  Superlogger.request_id = request.uuid.try(:gsub, '-', '')
end

#setup_session_id_for_logging(request) ⇒ Object



48
49
50
51
52
# File 'lib/superlogger/superlogger_middleware.rb', line 48

def setup_session_id_for_logging(request)
  return unless request.env['rack.session']&.id

  Superlogger.session_id = request.env['rack.session'].id.to_s
end