gen_event

In Erlang a gen_server has one module and one state. An event manager is the other shape: one process, any number of handlers, and handlers that are added and removed while the system runs. The manager owns no logic of its own; each handler is a module with the gen_event callbacks, and one notification reaches all of them. An audit log, a metrics sink and a live debugging printer can listen to the same events without knowing about each other. This is the last behaviour of the chapter that is not a process of its own: the GenServer lesson is the process, the gen_statem lesson is the process with phases, and this one is the dispatcher.

An event handler

The module below is a handler and the small demo in one file, so the program runs as one block: main/0 starts a manager registered as events, adds the module as a handler with a zero counter, and sends three events. The manager runs no handler code in the caller: a notification is a message, and the handler runs in the manager process:

audit.erl

-module(audit). -behaviour(gen_event). -export([main/0]). -export([init/1, handle_event/2, handle_call/2, handle_info/2, terminate/2]). main() -> {ok, _Pid} = gen_event:start_link({local, events}), ok = gen_event:add_handler(events, ?MODULE, 0), ok = gen_event:notify(events, {login, ada}), ok = gen_event:notify(events, {login, grace}), ok = gen_event:notify(events, logout), io:format("handlers: ~p~n", [gen_event:which_handlers(events)]), io:format("count: ~p~n", [gen_event:call(events, ?MODULE, count)]), ok = gen_event:delete_handler(events, ?MODULE, []), io:format("handlers after delete: ~p~n", [gen_event:which_handlers(events)]), ok = gen_event:notify(events, {login, alan}), ok = gen_event:stop(events). init(Count) -> {ok, Count}. handle_event(_Event, Count) -> {ok, Count + 1}. handle_call(count, Count) -> {ok, Count, Count}; handle_call(_Query, Count) -> {ok, undefined, Count}. handle_info(_Info, Count) -> {ok, Count}. terminate(_Reason, _Count) -> ok.

erlc audit.erl

erl -noshell -eval 'audit:main(), halt().'

handlers: [audit] count: 3 handlers after delete: []

The callbacks mirror the manager API. init/1 gets the arguments of add_handler/3 and answers the state of that handler. handle_event/2 gets one event and answers {ok, NewState}. handle_call/2 answers a synchronous question with {ok, Reply, NewState}, and the caller gets the reply. handle_info/2 receives a message that the manager forwarded to the handler, and terminate/2 runs when the handler is removed or the manager stops.

Adding and removing

add_handler/3 installs a handler at run time and answers ok, or {error, Reason} when its init/1 refuses. delete_handler/3 removes one and answers whatever its terminate/2 returns, so the third argument is both the goodbye message and the way to read that answer. which_handlers/1 lists the modules that are installed; a module may be installed more than once with different arguments, and then it appears once per instance. call/3 reaches one handler and notify/2 reaches all of them.

swap_handler/3 replaces a handler with another in one step, and add_sup_handler/3 makes the manager watch the process that added the handler: when that process dies, the handler is removed with it. A handler added by a short lived process is the leak to avoid, and the supervised form is the answer.

A handler that crashes

The property that separates this behaviour from the others is what a bad callback costs. A crash in a gen_server kills the server and every caller behind it; a crash in a handler removes that handler and nothing else. The manager calls the terminate callback of the handler with {error, {'EXIT', Reason}}, drops it, and goes on notifying the handlers that are left. This program has one handler and one event that makes it fail:

event_crash.erl

-module(event_crash). -behaviour(gen_event). -export([main/0]). -export([init/1, handle_event/2, handle_call/2, handle_info/2, terminate/2]). main() -> logger:set_primary_config(level, none), {ok, _Pid} = gen_event:start_link({local, events}), ok = gen_event:add_handler(events, ?MODULE, 0), ok = gen_event:notify(events, hello), io:format("count: ~p~n", [gen_event:call(events, ?MODULE, count)]), ok = gen_event:notify(events, explode), io:format("handlers: ~p~n", [gen_event:which_handlers(events)]), ok = gen_event:notify(events, hello), io:format("manager alive: ~p~n", [is_process_alive(whereis(events))]), ok = gen_event:stop(events). init(Count) -> {ok, Count}. handle_event(explode, _Count) -> error(explode); handle_event(_Event, Count) -> {ok, Count + 1}. handle_call(count, Count) -> {ok, Count, Count}; handle_call(_Query, Count) -> {ok, undefined, Count}. handle_info(_Info, Count) -> {ok, Count}. terminate(_Reason, _Count) -> io:format("terminate called~n"), ok.

erlc event_crash.erl

erl -noshell -eval 'event_crash:main(), halt().'

count: 1 terminate called handlers: [] manager alive: true

The handler is gone and the manager is not. That tolerance is also the trap: a handler that crashes on every event disappears from the system, and nothing but the crash report in the log says why. A handler that must never be lost either catches its own errors inside handle_event/2 and answers a state, or is added with add_sup_handler/3 by a supervisor that notices the loss.

When to use it

An event manager is the right tool for a signal that many parts of the system observe and none of them owns: a metrics counter, a logger, a live debugging printer that is attached during an incident. It is the wrong tool for a call that needs an answer computed by another process, because the manager serialises every handler in one process and one slow handler delays the rest.

A plain gen_server is the better default. One owner, one state, one place to look when the behaviour is wrong; the logger module that OTP itself ships is the tool for the same job, and the supervision trees lesson puts managers and servers in one tree.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is a gen_event manager?

    Answer

    A process that dispatches events to installed handlers

    The manager owns no logic: it keeps the list of handlers and delivers each notification to all of them.

  2. Which callback receives one notification?

    Answer

    handle_event/2

    notify/2 reaches handle_event/2 in every installed handler, and each answers its new state.

  3. What happens when a handler callback raises?

    Answer

    The handler is removed and the manager keeps running

    The manager calls the handler's terminate/2 with the error, drops that handler, and notifies the rest.

  4. What does delete_handler/3 answer?

    Answer

    Whatever the handler's terminate/2 returns

    The third argument is the goodbye message, and the answer of terminate/2 comes back to the caller.

  5. Which call makes the manager remove a handler when the process that added it dies?

    Answer

    add_sup_handler/3

    The supervised form watches the adding process and removes the handler with it.

  6. Why can one slow handler be a problem?

    Answer

    It blocks the other handlers of the same manager

    The handlers run one after another in the manager process, so the slowest one sets the pace.

  7. What does this module print? -module(q1). -export([main/0]). main() -> {ok, _Pid} = gen_event:start_link({local, events}), io:format("~p~n", [gen_event:which_handlers(events)]).

    Answer

    []

    A new manager has no handlers, and which_handlers/1 answers the empty list.

  8. What does this module print? -module(q2). -export([main/0]). main() -> {ok, _Pid} = gen_event:start_link({local, events}), io:format("~p~n", [gen_event:notify(events, hello)]).

    Answer

    ok

    A notification with no handlers is still a successful send, and notify/2 answers ok.

  9. What does this module print? -module(q3). -behaviour(gen_event). -export([main/0]). -export([init/1, handle_event/2, handle_call/2, handle_info/2, terminate/2]). main() -> {ok, _Pid} = gen_event:start_link({local, events}), ok = gen_event:add_handler(events, ?MODULE, 0), ok = gen_event:notify(events, a), ok = gen_event:notify(events, b), ok = gen_event:notify(events, c), io:format("~p~n", [gen_event:call(events, ?MODULE, count)]). init(Count) -> {ok, Count}. handle_event(_Event, Count) -> {ok, Count + 1}. handle_call(count, Count) -> {ok, Count, Count}; handle_call(_Query, Count) -> {ok, undefined, Count}. handle_info(_Info, Count) -> {ok, Count}. terminate(_Reason, _Count) -> ok.

    Answer

    3

    Each notification adds one to the handler state, and the call answers the third value.

  10. What does this module print? -module(q4). -behaviour(gen_event). -export([main/0]). -export([init/1, handle_event/2, handle_call/2, handle_info/2, terminate/2]). main() -> logger:set_primary_config(level, none), {ok, _Pid} = gen_event:start_link({local, events}), ok = gen_event:add_handler(events, ?MODULE, 0), ok = gen_event:notify(events, explode), io:format("~p~n", [gen_event:which_handlers(events)]). init(Count) -> {ok, Count}. handle_event(explode, _Count) -> error(explode); handle_event(_Event, Count) -> {ok, Count + 1}. handle_call(count, Count) -> {ok, Count, Count}; handle_call(_Query, Count) -> {ok, undefined, Count}. handle_info(_Info, Count) -> {ok, Count}. terminate(_Reason, _Count) -> ok.

    Answer

    []

    The failing handler is removed by the manager, so no handler is left installed.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev