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: Logger.new(STDOUT)}).get("https://example.com/")

Binary bodies (IO/Enumerable request sources and binary-encoded responses) are formatted using the binary_formatter option instead of being dumped raw. Available formatters:

  • :stats (default) — logs BINARY DATA (N bytes)

  • :base64 — logs BINARY DATA (N bytes)\n<base64>

  • Proc — calls the proc with the raw binary string

Examples:

Custom binary formatter

HTTP.use(logging: {logger: Logger.new(STDOUT), binary_formatter: :base64})

Defined Under Namespace

Classes: BodyLogger, NullLogger

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from HTTP::Feature

#around_request, #on_error, #on_request

Constructor Details

#initialize(logger: NullLogger.new, binary_formatter: :stats) ⇒ Logging

Initializes the Logging feature

Examples:

Logging.new(logger: Logger.new(STDOUT))

With binary formatter

Logging.new(logger: Logger.new(STDOUT), binary_formatter: :base64)

Parameters:

  • logger (#info, #debug) (defaults to: NullLogger.new)

    logger instance

  • binary_formatter (:stats, :base64, #call) (defaults to: :stats)

    how to log binary bodies



60
61
62
63
64
# File 'lib/http/features/logging.rb', line 60

def initialize(logger: NullLogger.new, binary_formatter: :stats)
  super()
  @logger = logger
  @binary_formatter = validate_binary_formatter!(binary_formatter)
end

Instance Attribute Details

#logger#info, #debug (readonly)

The logger instance

Examples:

feature.logger

Returns:

  • (#info, #debug)

    the logger instance



46
47
48
# File 'lib/http/features/logging.rb', line 46

def logger
  @logger
end

Instance Method Details

#wrap_request(request) ⇒ HTTP::Request

Logs and returns the request

Examples:

feature.wrap_request(request)

Parameters:

Returns:



74
75
76
77
78
79
# File 'lib/http/features/logging.rb', line 74

def wrap_request(request)
  logger.info { format("> %s %s", String(request.verb).upcase, request.uri) }
  log_request_details(request)

  request
end

#wrap_response(response) ⇒ HTTP::Response

Logs and returns the response

Examples:

feature.wrap_response(response)

Parameters:

Returns:



89
90
91
92
93
94
95
96
97
98
# File 'lib/http/features/logging.rb', line 89

def wrap_response(response)
  logger.info { "< #{response.status}" }

  return log_response_body_inline(response) unless response.body.is_a?(Response::Body)

  logger.debug { stringify_headers(response.headers) }
  return response unless logger.debug?

  Response.new(**logged_response_options(response)) # steep:ignore
end