Instrumenting an Elixir Phoenix Pow Application to measure user session count

Instrumenting an Elixir Phoenix Pow Application to measure user session count

If you have generated an Elixir Phoenix project with version 1.5.0 or later of the project generator (phx_new), you will already have telemetry and telemetry-poller installed.

Create a module e.g. measurements.ex with the following content:

defmodule MyApp.Measurements do

  def dispatch_session_count() do
    # emit a telemetry event when called
    num_sessions = length(Pow.Store.CredentialsCache.users([otp_app: :my_app], MyApp.Users.User))

    :telemetry.execute(
      [:my_app, :session_count],
      %{count: num_sessions},
      %{}
    )
  end
end

Then edit telemetry.ex and in the def metricsblock, add:

  # Pow User Metrics
      summary("my_app.session_count.count"),

in the defp periodic_measurements block, add:

{MyApp.Measurements, :dispatch_session_count, []}

Now you can head to http://localhost:4000/dashboard/ and find your new metric displayed under "metrics": my_app.session_count.count.

Photo by Darling Arias on Unsplash

Show Comments