Class: Dcmgr::Rack::RequestLogger

Inherits:
Object
  • Object
show all
Defined in:
lib/dcmgr/rack/request_logger.rb

Overview

Rack middleware for logging each API request.

Constant Summary collapse

HTTP_X_VDC_REQUEST_ID =
'HTTP_X_VDC_REQUEST_ID'.freeze
HEADER_X_VDC_REQUEST_ID =
'X-VDC-Request-ID'.freeze
RACK_REQUEST_LOG_KEY =
'vdc.request_log'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(app, with_header = true) ⇒ RequestLogger

Returns a new instance of RequestLogger.

Raises:

  • (TypeError)


12
13
14
15
16
# File 'lib/dcmgr/rack/request_logger.rb', line 12

def initialize(app, with_header=true)
  raise TypeError unless app.is_a?(Dcmgr::Endpoints::CoreAPI)
  @app = app
  @with_header = with_header
end

Instance Method Details

#_call(env) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/dcmgr/rack/request_logger.rb', line 22

def _call(env)
  request = ::Rack::Request.new(env)
  env[RACK_REQUEST_LOG_KEY] = @log = Dcmgr::Models::RequestLog.new
  log_env(request)
  begin
    ret = @app.call(env)
    @log.response_status = ret[0]
    @log.response_msg = ''

    # inject X-VDC-Request-ID header
    if @with_header
      ret[1] = (ret[1] || {}).merge({HEADER_X_VDC_REQUEST_ID=>@log.request_id})
    end
    return ret
  rescue ::Exception => e
    @log.response_status = 999
    @log.response_msg = e.message
    raise e
  ensure
    @log.class.db.transaction do
      @log.save
    end
  end
end

#call(env) ⇒ Object



18
19
20
# File 'lib/dcmgr/rack/request_logger.rb', line 18

def call(env)
  dup._call(env)
end