Integrating AppSignal with Phoenix Liveview tutorial
Right, you want to use Appsignal to monitor your Phoenix Liveview application? Here's how you do it.
Note: This guide assumes you're on Liveview 0.17.5 or newer because we depend on the new liveview event hooks.
First install the appsignal_phoenix
package. Because this package already depends on the appsignal
package, there's no need for you to manually add it.
defp deps do
[
{:appsignal_phoenix, "~> 2.0"},
Then we're going to hook into the lifecycle in two spots. One for the mount
event, and one for the handle_event
.
In your myproject_web.ex
add two on_mount
handlers.
def live_view do
quote do
use Phoenix.LiveView,
layout: {GamingWeb.LayoutView, "live.html"}
on_mount(GamingWeb.InitAssigns)
on_mount(GamingWeb.Appsignal)
unquote(view_helpers())
end
end
Tracking mount events
Let's start by creating the InitAssigns
module.
defmodule GamingWeb.InitAssigns do
@moduledoc false
import Phoenix.LiveView
import Appsignal.Phoenix.LiveView, only: [live_view_action: 5]
def on_mount(:default, params, session, socket) do
# here's where we're calling appsignal instrumentation
live_view_action(socket.view, "mount", params, socket, fn ->
socket =
socket
|> assign_new(:current_user, fn ->
get_user(session["user_token"])
end)
{:cont, socket}
end)
end
end
We're done, every mount
will be tracked properly on Appsignal.
Tracking handle_event events
We're going to track the handle_event
lifecycle event. If you want you can track others like:
defmodule GamingWeb.Appsignal do
@moduledoc false
import Phoenix.LiveView
import Appsignal.Phoenix.LiveView, only: [live_view_action: 5]
def on_mount(:default, _params, _session, socket) do
socket =
attach_hook(socket, :mount_hook, :handle_event, fn
event, params, socket ->
live_view_action(socket.view, event, params, socket, fn ->
{:cont, socket}
end)
end)
{:cont, socket}
end
end
And we're done. Here I'm tracking a simple form event named submit
.
def handle_event("submit", %{"waitlist" => params}, socket) do
{:noreply, socket}
end