Class: TocDoc::Middleware::Logging

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/toc_doc/http/middleware/logging.rb

Overview

Faraday middleware that logs the outcome of every HTTP request.

Placed between RaiseError (outermost) and the retry middleware so that each logical request is logged exactly once — after all retry attempts have been exhausted — rather than once per attempt.

Stack order (outermost first): RaiseError > Logging > retry > JSON parse > adapter

Log format: TocDoc: GET /path.json -> 200 (42ms) # success → logger.info TocDoc: GET /path.json -> error: Msg (42ms) # failure → logger.warn

When no logger is provided the middleware is a no-op.

Examples:

Attach a custom logger

TocDoc.configure { |c| c.logger = Logger.new($stdout) }

Use the :stdout shorthand

TocDoc.configure { |c| c.logger = :stdout }

Instance Method Summary collapse

Constructor Details

#initialize(app, logger: nil) ⇒ Logging

Returns a new instance of Logging.

Parameters:

  • app (#call)

    the next middleware in the stack

  • logger (Logger, nil) (defaults to: nil)

    the logger to write to; +nil+ disables logging



30
31
32
33
# File 'lib/toc_doc/http/middleware/logging.rb', line 30

def initialize(app, logger: nil)
  super(app)
  @logger = logger
end

Instance Method Details

#call(env) ⇒ Faraday::Response

Calls the next middleware, measures elapsed time, and logs the outcome.

Parameters:

  • env (Faraday::Env)

    the Faraday request environment

Returns:

  • (Faraday::Response)

    the response on success

Raises:

  • (StandardError)

    re-raises any exception after logging it



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/toc_doc/http/middleware/logging.rb', line 40

def call(env)
  start    = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  response = @app.call(env)
  duration = duration_ms(start)
  log_request(env, response.status, duration)
  response
rescue StandardError => e
  duration = duration_ms(start)
  log_error(env, e, duration)
  raise
end