Class: HTTP::Features::Logging

Inherits:
HTTP::Feature show all
Defined in:
lib/http/features/logging.rb

Overview

Log requests and responses. Request verb and uri, and Response status are logged at info, and the headers and bodies of both are logged at debug. Be sure to specify the logger when enabling the feature:

HTTP.use(logging: Logger.new(STDOUT)).get("https://example.com/")

Defined Under Namespace

Classes: NullLogger

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger: NullLogger.new) ⇒ Logging

Returns a new instance of Logging.



14
15
16
# File 'lib/http/features/logging.rb', line 14

def initialize(logger: NullLogger.new)
  @logger = logger
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



12
13
14
# File 'lib/http/features/logging.rb', line 12

def logger
  @logger
end

Instance Method Details

#wrap_request(request) ⇒ Object



18
19
20
21
22
23
24
25
26
27
# File 'lib/http/features/logging.rb', line 18

def wrap_request(request)
  logger.info { "> #{request.verb.to_s.upcase} #{request.uri}" }
  logger.debug do
    headers = request.headers.map { |name, value| "#{name}: #{value}" }.join("\n")
    body = request.body.source

    headers + "\n\n" + body.to_s
  end
  request
end

#wrap_response(response) ⇒ Object



29
30
31
32
33
34
35
36
37
38
# File 'lib/http/features/logging.rb', line 29

def wrap_response(response)
  logger.info { "< #{response.status}" }
  logger.debug do
    headers = response.headers.map { |name, value| "#{name}: #{value}" }.join("\n")
    body = response.body.to_s

    headers + "\n\n" + body
  end
  response
end