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 tracking
  • prepare_request_data/4: Prepares a RequestLog struct with relevant request and session information
  • format_ip/1: Formats IP addresses to string representation
  • remote_ip/1: Extracts the remote IP address from the connection, considering X-Forwarded-For headers
  • get_header/3: Safely retrieves a header value from the connection
  • generate_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:

  1. Records the start time of the request.
  2. Manages session tracking by creating or retrieving a session ID and start time.
  3. 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: The Plug.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.