23
votes

Given a simple GenServer process.

defmodule KVServer do
  use GenServer

  def start do
    GenServer.start(__MODULE__, %{}, name: :kv_server)
  end

  def store(k, v) do
    GenServer.cast(:kv_server, {:store, k, v})
  end

  def handle_cast({:store, k, v}, state) do
    {:noreply, Map.put(state, k, v)}
  end
end

I can get the current process state using :sys.get_status/1

iex(1)> {:ok, pid} = KVServer.start
{:ok, #PID<0.119.0>}
iex(2)> KVServer.store(:a, 1)
:ok
iex(3)> KVServer.store(:b, 2)
:ok
iex(4)> {_,_,_,[_,_,_,_,[_,_,{_,[{_,state}]}]]} = :sys.get_status(pid)
...
iex(5)> state
%{a: 1, b: 2}

Just wondering is there an easier way provided by Elixir to get a GenServer process's current state?

1

1 Answers

39
votes

Use :sys.get_state/1:

iex(1)> {:ok, pid} = KVServer.start
{:ok, #PID<0.86.0>}
iex(2)> KVServer.store(:a, 1)
:ok
iex(3)> KVServer.store(:b, 2)
:ok
iex(4)> :sys.get_state(pid)
%{a: 1, b: 2}