Class: Fbe::Middleware::Trace

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/fbe/middleware/trace.rb

Overview

Faraday middleware that traces all API calls.

This middleware records all HTTP requests and responses in a trace array, capturing method, URL, status, and timing information for debugging and monitoring purposes.

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2024-2025 Zerocracy

License

MIT

Examples:

Usage in Faraday middleware stack

trace = []
connection = Faraday.new do |f|
  f.use Fbe::Middleware::Trace, trace
end
connection.get('/api/endpoint')
trace.first[:method] #=> :get
trace.first[:url] #=> 'https://example.com/api/endpoint'
trace.first[:status] #=> 200

Instance Method Summary collapse

Constructor Details

#initialize(app, trace, all: true) ⇒ Trace

Initializes the trace middleware.

Parameters:

  • app (Object)

    The next middleware in the stack

  • trace (Array)

    The array to store trace entries

  • all (Boolean) (defaults to: true)

    Print ALL requests, even very fast?



35
36
37
38
39
# File 'lib/fbe/middleware/trace.rb', line 35

def initialize(app, trace, all: true)
  super(app)
  @trace = trace
  @all = all
end

Instance Method Details

#call(env) ⇒ Faraday::Response

Processes the HTTP request and records trace information.

Parameters:

  • env (Faraday::Env)

    The request environment

Returns:

  • (Faraday::Response)

    The response from the next middleware



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/fbe/middleware/trace.rb', line 45

def call(env)
  entry = {
    method: env.method,
    url: env.url.to_s,
    started_at: Time.now
  }
  @app.call(env).on_complete do |response_env|
    finished = Time.now
    duration = finished - entry[:started_at]
    if duration > 0.01 || @all
      entry[:status] = response_env.status
      entry[:finished_at] = finished
      entry[:duration] = duration
      @trace << entry
    end
  end
end