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) ⇒ Trace

Initializes the trace middleware.

Parameters:

  • app (Object)

    The next middleware in the stack

  • trace (Array)

    The array to store trace entries



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

def initialize(app, trace)
  super(app)
  @trace = trace
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



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

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