Class: InboundRequestsLoggerMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_api_logger/inbound_requests_logger_middleware.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, only_state_change: true, path_regexp: /.*/, skip_body_regexp: nil) ⇒ InboundRequestsLoggerMiddleware

Returns a new instance of InboundRequestsLoggerMiddleware.



4
5
6
7
8
9
# File 'lib/rails_api_logger/inbound_requests_logger_middleware.rb', line 4

def initialize(app, only_state_change: true, path_regexp: /.*/, skip_body_regexp: nil)
  @app = app
  self.only_state_change = only_state_change
  self.path_regexp = path_regexp
  self.skip_body_regexp = skip_body_regexp
end

Instance Attribute Details

#only_state_changeObject

Returns the value of attribute only_state_change.



2
3
4
# File 'lib/rails_api_logger/inbound_requests_logger_middleware.rb', line 2

def only_state_change
  @only_state_change
end

#path_regexpObject

Returns the value of attribute path_regexp.



2
3
4
# File 'lib/rails_api_logger/inbound_requests_logger_middleware.rb', line 2

def path_regexp
  @path_regexp
end

#skip_body_regexpObject

Returns the value of attribute skip_body_regexp.



2
3
4
# File 'lib/rails_api_logger/inbound_requests_logger_middleware.rb', line 2

def skip_body_regexp
  @skip_body_regexp
end

Instance Method Details

#call(env) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/rails_api_logger/inbound_requests_logger_middleware.rb', line 11

def call(env)
  request = ActionDispatch::Request.new(env)
  logging = log?(env, request)
  if logging
    env["INBOUND_REQUEST_LOG"] = InboundRequestLog.from_request(request)
    request.body.rewind
  end
  status, headers, body = @app.call(env)
  if logging
    updates = {response_code: status, ended_at: Time.current}
    updates[:response_body] = parsed_body(body) if log_response_body?(env)
    # this usually works. let's be optimistic.
    begin
      env["INBOUND_REQUEST_LOG"].update_columns(updates)
    rescue JSON::GeneratorError => _e # this can be raised by activerecord if the string is not UTF-8.
      env["INBOUND_REQUEST_LOG"].update_columns(updates.except(:response_body))
    end
  end
  [status, headers, body]
end