View Source Sentry.Plug.LiveViewContext (Sentry v12.0.3)

A Plug that stores OpenTelemetry context in the session for LiveView distributed tracing.

This plug serializes the current OpenTelemetry context into the session, allowing LiveView processes to restore the trace context and maintain distributed tracing continuity.

Why This Is Needed

When a browser requests a page with a LiveView, the HTTP request comes with distributed tracing headers (e.g., sentry-trace, traceparent). OpenTelemetry propagators extract these headers and attach the trace context to the request process.

However, Phoenix LiveView creates fresh BEAM processes for each lifecycle callback (mount, handle_params, etc.). These new processes don't automatically inherit the OpenTelemetry context from the HTTP request process, causing trace continuity to break.

This plug bridges that gap by:

  1. Serializing the current trace context into the session before LiveView renders
  2. Allowing Sentry.OpenTelemetry.LiveViewPropagator to restore the context in LiveView processes

Usage

Step 1: Set up telemetry handlers

In your application's start/2 callback, call Sentry.OpenTelemetry.LiveViewPropagator.setup/0 BEFORE OpentelemetryPhoenix.setup/1:

def start(_type, _args) do
  # Set up Sentry's LiveView context propagation FIRST
  Sentry.OpenTelemetry.LiveViewPropagator.setup()

  # Then set up OpentelemetryPhoenix
  OpentelemetryPhoenix.setup(adapter: :bandit)

  children = [
    # ...
  ]

  Supervisor.start_link(children, strategy: :one_for_one)
end

Step 2: Add this plug to your router

Add this plug to your router pipeline that serves LiveViews, after the session plug and before LiveView routes:

pipeline :browser do
  plug :accepts, ["html"]
  plug :fetch_session
  plug :fetch_live_flash
  plug :put_root_layout, html: {MyAppWeb.Layouts, :root}
  plug :protect_from_forgery
  plug :put_secure_browser_headers
  plug Sentry.Plug.LiveViewContext  # Add this line
end

How It Works

  1. This plug serializes the current trace context into the session during the HTTP request phase (static LiveView render).

  2. Sentry.OpenTelemetry.LiveViewPropagator attaches telemetry handlers that run BEFORE opentelemetry_phoenix creates spans.

  3. When LiveView lifecycle events fire (mount, handle_params, handle_event), the propagator extracts the trace context from the session and attaches it to the process before opentelemetry_phoenix creates its spans.

  4. All subsequent OpenTelemetry spans created in the LiveView process will now share the same trace ID as the original HTTP request.

Session Key

The plug stores the serialized context under "__sentry_lv_ctx__" in the session. The context is small (just trace ID and span ID) and will naturally expire with the session. It's kept in the session so that WebSocket LiveView connections can restore the trace context.

Available since v10.8.0.