Run code upon messages (first) arriving in a Process

Hey there,

Is there any way to install a ‘hook’ in a process that will do something every time a message arrives in the actor? For example, could I make the process to print out “Message arrived! It is currently at position X in the mailbox” every time a message arrives. I’m relatively new to Elixir and until now I’ve not yet found info on how this could be done.

To be clear, I do not want to do something when the message is actually being handled (by receive). I want to do something when it first arrives in the Process and is put in the mailbox.

Thanks! :smiley:

You can trace a process :receiving messages, and the messages would be printed out.

iex> :dbg.tracer()
{:ok, #PID<0.158.0>}

iex> pid = spawn(fn -> receive do _ -> :ok end end)
#PID<0.161.0>

iex> :dbg.p(pid, [:r])
{:ok, [{:matched, :nonode@nohost, 1}]}

iex> send(pid, "hello from #{inspect(self)}")
# (<0.161.0>) << <<"hello from #PID<0.109.0>">>
"hello from #PID<0.109.0>"

You can check out what else you can do on Erlang -- dbg

I do not believe that this is possible, the only way that I know of to interact with a mailbox is to receive from it, and that is of course only doable within the process associated with the mailbox.

1 Like

Does this print when the message arrives or when receive is called on the message?