View Source PhoenixAnalytics.Plugs.RequestTracker (PhoenixAnalytics v0.3.2)
A Plug module for tracking and logging HTTP requests in a Phoenix application.
This module provides functionality to:
- Measure the duration of each request
- Collect relevant request data (method, path, status code, etc.)
- Track session information
- Asynchronously broadcast the collected data using PubSub
Key components:
call/2
: The main plug function that wraps the request, measures its duration, and manages session trackingprepare_request_data/4
: Prepares aRequestLog
struct with relevant request and session informationformat_ip/1
: Formats IP addresses to string representationremote_ip/1
: Extracts the remote IP address from the connection, considering X-Forwarded-For headersget_header/3
: Safely retrieves a header value from the connectiongenerate_uuid/0
: Generates a unique identifier for new sessions
Usage: Add this plug to your endpoint straight after static plugs or router to start tracking requests:
plug PhoenixAnalytics.Plugs.RequestTracker
Using it in directly in router possible as well, but than you won't be able to track static files.
pipeline :browser do
...
plug PhoenixAnalytics.Plugs.RequestTracker
end
Note: This module uses the PhoenixAnalytics.Services.PubSub
module to broadcast
request data, allowing for distributed apps share requests and analysis.
Summary
Functions
Main plug function that wraps the request, measures its duration, and manages session tracking.
Functions
Main plug function that wraps the request, measures its duration, and manages session tracking.
This function:
- Records the start time of the request.
- Manages session tracking by creating or retrieving a session ID and start time.
- Registers a before_send callback to:
- Calculate the request duration and session duration.
- Prepare request and session data.
- Asynchronously broadcast the data using PubSub.
The function catches any errors during data preparation or broadcasting to ensure the request processing continues even if tracking fails.
Parameters
conn
: ThePlug.Conn
struct representing the current connection._opts
: Options passed to the plug (unused in this implementation).
Returns
Returns the conn
struct, potentially modified by subsequent plugs or handlers.