4 Gen_Event Behaviour
This chapter should be read in conjunction with
gen_event(3)
, where all interface functions and callback functions are described in detail.4.1 Event Handling Principles
In OTP, an event manager is a named object to which events can be sent. An event could be, for example, an error, an alarm or some information that should be logged.
In the event manager, zero, one or several event handlers are installed. When the event managar is notified about an event, the event will be processed by all the installed event handlers. For example, an event manager for handling errors can by default have a handler installed which writes error messages to the terminal. If the error messages during a certain period should be saved to a file as well, the user adds another event handler which does this. When logging to file is no longer necessary, this event handler is deleted.
An event manager is implemented as a process and each event handler is implemented as a callback module.
The event manager essentially maintains a list of
{Module, State}
pairs, where eachModule
is an event handler, andState
the internal state of that event handler.4.2 Example
The callback module for the event handler writing error messages to the terminal could look like:
-module(terminal_logger). -behaviour(gen_event). -export([init/1, handle_event/2, terminate/2]). init(_Args) -> {ok, []}. handle_event(ErrorMsg, State) -> io:format("***Error*** ~p~n", [ErrorMsg]), {ok, State}. terminate(_Args, _State) -> ok.The callback module for the event handler writing error messages to a file could look like:
-module(file_logger). -behaviour(gen_event). -export([init/1, handle_event/2, terminate/2]). init(File) -> {ok, Fd} = file:open(File, read), {ok, Fd}. handle_event(ErrorMsg, Fd) -> io:format(Fd, "***Error*** ~p~n", [ErrorMsg]), {ok, Fd}. terminate(_Args, Fd) -> file:close(Fd).The code is explained in the next sections.
4.3 Starting an Event Manager
Here is an example of how an event manager for handling errors, as described in the example above, is started from the shell:
1> gen_event:start_link({local, error_man}). {ok,<0.30.0>}This function spawns and links to a new process, an event manager.
The argument,
{local, error_man}
specifies the name. In this case, the event manager will be locally registered aserror_man
.If the name is omitted, the event manager is not registered. Instead its pid must be used. The name could also be given as
{global, Name}
, in which case the event manager is registered usingglobal:register_name/2
.4.4 Adding an Event Handler
2> gen_event:add_handler(error_man, terminal_logger, []). okThis function sends a message to the event manager registered as
error_man
, telling it to add the event handlerterminal_logger
. The event manager will call the callback functionterminal_logger:init([])
, where the argument [] is the third argument toadd_handler
.init
is expected to return{ok, State}
, whereState
is the internal state fo the event handler.init(_Args) -> {ok, []}.Here,
init
does not need any indata and ignores its argument. Also, forterminal_logger
the internal state is not used. Forfile_logger
, the internal state is used to save the open file descriptor.init(_Args) -> {ok, Fd} = file:open(File, read), {ok, Fd}.4.5 Notifying About Events
3> gen_event:notify(error_man, no_reply). ***Error*** no_reply ok
error_man
is the name of the event manager andno_reply
is the event.The event is made into a message and sent to the event manager. When the event is received, the event manager calls
handle_event(Event, State)
for each installed event handler, in the same order as they were added. The function is expected to return a tuple{ok, State1}
, whereState1
is a new value for the state of the event handler.In
terminal_logger
:handle_event(ErrorMsg, State) -> io:format("***Error*** ~p~n", [ErrorMsg]), {ok, State}.In
file_logger
:handle_event(ErrorMsg, Fd) -> io:format(Fd, "***Error*** ~p~n", [ErrorMsg]), {ok, Fd}.4.6 Deleting an Event Handler
4> gen_event:delete_handler(error_man, terminal_logger, []). okThis function sends a message to the event manager registered as
error_man
, telling it to delete the event handlerterminal_logger
. The event manager will call the callback functionterminal_logger:terminate([], State)
, where the argument [] is the third argument todelete_handler
.terminate
should be the opposite ofinit
and do any necessary cleaning up. Its return value is ignored.For
terminal_logger
, no cleaning up is necessary:terminate(_Args, _State) -> ok.For
file_logger
, the file descriptor opened ininit
needs to be closed:terminate(_Args, Fd) -> file:close(Fd).4.7 Stopping
If the event manager is part of a supervision tree, no stop function is needed. The event manager will automatically be terminated by its supervisor calling
exit(Pid, shutdown)
.An event manager can also be stopped by calling:
> gen_event:stop(error_man). okWhen an event manager is stopped, it will give each of the installed event handlers the chance to clean up by calling
terminate/2
, the same way as when deleting a handler.