Class: PierLogging::RequestLogger

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, logger = PierLogging::Logger.new(STDOUT)) ⇒ RequestLogger

Returns a new instance of RequestLogger.

[View source]

5
6
7
8
# File 'lib/pier_logging/request_logger.rb', line 5

def initialize(app, logger = PierLogging::Logger.new(STDOUT))
  @app = app
  @logger = logger
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.


3
4
5
# File 'lib/pier_logging/request_logger.rb', line 3

def logger
  @logger
end

Instance Method Details

#call(env) ⇒ Object

[View source]

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/pier_logging/request_logger.rb', line 10

def call(env)
  starts_at = Time.now.utc
  begin
    status, type, body = response = @app.call(env)
    log([env, status, type, body, starts_at, Time.now.utc, nil])
  rescue Exception => exception
    status = determine_status_code_from_exception(exception)
    type = determine_type_from_exception(exception)
    body = determine_body_from_exception(exception)
    log([env, status, type, body, starts_at, Time.now.utc, exception])
    raise exception
  end

  response
end

#log(args) ⇒ Object

[View source]

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/pier_logging/request_logger.rb', line 27

def log(args)
  return unless PierLogging.request_logger_configuration.enabled

  env, status, type, body, starts_at, ends_at, _ = args
  request = Rack::Request.new(env)
  request_headers = get_request_headers_from_env(env)
  info = {
    message: build_message_from_request(request),
    type: 'http',
    duration: ((ends_at - starts_at)*1000).to_i,
    context: {
      user: (request_headers),
      request_id: env['action_dispatch.request_id'],
      correlation_id: get_correlation_id(env, request_headers)
    },
    request: {
      headers: request_headers,
      href: request.url,
      query_string: request.query_string,
      body: request_body(request.path, request.body)
    },
    response: {
      status: status,
      body: response_body(request.path, body),
      type: type['Content-Type'],
    }
  }
  logger.info info
rescue StandardError => error
  # We should never fall in this part as the only errors that could result in this are errors
  # in our logger (inside this same method)
  @logger.error(error.message)
end