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_request_body_regexp: nil, skip_response_body_regexp: nil) ⇒ InboundRequestsLoggerMiddleware

Returns a new instance of InboundRequestsLoggerMiddleware.



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

def initialize(app, only_state_change: true,
  path_regexp: /.*/,
  skip_request_body_regexp: nil,
  skip_response_body_regexp: nil)
  @app = app
  self.only_state_change = only_state_change
  self.path_regexp = path_regexp
  self.skip_request_body_regexp = skip_request_body_regexp
  self.skip_response_body_regexp = skip_response_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_request_body_regexpObject

Returns the value of attribute skip_request_body_regexp.



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

def skip_request_body_regexp
  @skip_request_body_regexp
end

#skip_response_body_regexpObject

Returns the value of attribute skip_response_body_regexp.



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

def skip_response_body_regexp
  @skip_response_body_regexp
end

Instance Method Details

#call(env) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rails_api_logger/inbound_requests_logger_middleware.rb', line 15

def call(env)
  request = ActionDispatch::Request.new(env)
  logging = log?(env, request)
  if logging
    env["INBOUND_REQUEST_LOG"] = InboundRequestLog.from_request(request, skip_request_body: skip_request_body?(env))
    request.body.rewind
  end
  status, headers, body = @app.call(env)
  if logging
    updates = {response_code: status, ended_at: Time.current}
    updates[:response_body] = if skip_response_body?(env)
      "[Skipped]"
    else
      parsed_body(body)
    end
    # 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