diff --git a/lib/sentry/live_view_hook.ex b/lib/sentry/live_view_hook.ex index a2bbc9f8..fc9e3d40 100644 --- a/lib/sentry/live_view_hook.ex +++ b/lib/sentry/live_view_hook.ex @@ -68,17 +68,17 @@ if Code.ensure_loaded?(Phoenix.LiveView) do data: params }) - if uri = get_connect_info(socket, :uri) do + if uri = get_connect_info_if_root(socket, :uri) do Context.set_request_context(%{url: URI.to_string(uri)}) end - if user_agent = get_connect_info(socket, :user_agent) do + if user_agent = get_connect_info_if_root(socket, :user_agent) do Context.set_extra_context(%{user_agent: user_agent}) end # :peer_data returns t:Plug.Conn.Adapter.peer_data/0. # https://hexdocs.pm/plug/Plug.Conn.Adapter.html#t:peer_data/0 - if ip_address = socket |> get_connect_info(:peer_data) |> get_safe_ip_address() do + if ip_address = socket |> get_connect_info_if_root(:peer_data) |> get_safe_ip_address() do Context.set_user_context(%{ip_address: ip_address}) end @@ -132,6 +132,13 @@ if Code.ensure_loaded?(Phoenix.LiveView) do {:cont, socket} end + defp get_connect_info_if_root(socket, key) do + case socket.parent_pid do + nil -> get_connect_info(socket, key) + pid when is_pid(pid) -> nil + end + end + defp maybe_attach_hook_handle_params(socket) do case socket.parent_pid do nil -> attach_hook(socket, __MODULE__, :handle_params, &handle_params_hook/3) diff --git a/test/sentry/live_view_hook_test.exs b/test/sentry/live_view_hook_test.exs index 4c7c6e7a..6c9c5191 100644 --- a/test/sentry/live_view_hook_test.exs +++ b/test/sentry/live_view_hook_test.exs @@ -6,6 +6,7 @@ defmodule SentryTest.Live do def render(assigns) do ~H"""

Testing Sentry hooks

+ <.live_component module={SentryTest.LiveComponent} id="lc" /> """ end @@ -22,6 +23,14 @@ defmodule SentryTest.Live do end end +defmodule SentryTest.LiveComponent do + use Phoenix.LiveComponent + + def render(assigns) do + ~H"

I'm a LiveComponent

" + end +end + defmodule SentryTest.Router do use Phoenix.Router import Phoenix.LiveView.Router @@ -64,9 +73,7 @@ defmodule Sentry.LiveViewHookTest do end test "attaches the right context", %{conn: conn} do - conn = - conn - |> Plug.Conn.put_req_header("user-agent", "sentry-testing 1.0") + conn = Plug.Conn.put_req_header(conn, "user-agent", "sentry-testing 1.0") {:ok, view, html} = live(conn, "/hook_test") assert html =~ "

Testing Sentry hooks

" @@ -113,6 +120,12 @@ defmodule Sentry.LiveViewHookTest do assert info_breadcrumb.message == ~s(:test_message) end + test "works with live components", %{conn: conn} do + {:ok, _view, html} = live(conn, "/hook_test") + assert html =~ "

Testing Sentry hooks

" + assert html =~ "I'm a LiveComponent" + end + defp get_sentry_context(view) do {:dictionary, pdict} = Process.info(view.pid, :dictionary)