Observability and logging
A running Erlang system tells you what it is doing in four ways: through its log, through the shape of its processes, through the traces you ask for, and through the counters the runtime keeps. None of them needs a debugger attached, which is what makes them usable on the machine that has the problem. The debugging lesson covers the interactive side; this one is the side a release runs with.
The logger
logger is the logging application of OTP. A message has a level, and both the primary configuration and each handler filter by it, so one handler can keep every warning while another writes only errors to a file. The default handler prints a line with a timestamp and metadata, which is right for a service and awkward in a transcript, so the program below replaces it with a handler that prints the level and the message term:
levels.erl
-module(levels). -export([main/0, log/2]). main() -> logger:remove_handler(default), ok = logger:add_handler(print, ?MODULE, #{level => all}), ok = logger:set_primary_config(level, info), logger:debug("debug is hidden"), logger:info("an info message"), logger:warning(#{what => disk_full}), logger:error("an error"). log(#{level := Level, msg := Msg}, _Config) -> io:format("~p: ~p~n", [Level, Msg]).
erlc levels.erl
erl -noshell -eval 'levels:main(), halt().'
info: {string,"an info message"} warning: {report,#{what => disk_full}} error: {string,"an error"}
The debug line never reached the handler, because the primary level is info and debug is below it. The shape of the message is worth reading: a string arrives as {string, Text} and a map as {report, Map}, and a handler that logs the term gets both without parsing. A real handler writes to a file or forwards to a collector, and logger:set_handler_config/3 changes its level at run time without a restart.
The mailbox of a process
The first number to look at when a process is slow is the length of its mailbox. process_info(Pid, message_queue_len) answers a small tuple, and the program below fills its own mailbox and then drains it:
mailbox.erl
-module(mailbox). -export([main/0]). main() -> Self = self(), [Self ! {job, N} || N <- [1, 2, 3]], io:format("queued: ~p~n", [queue()]), drain(), io:format("after the drain: ~p~n", [queue()]), io:format("status: ~p~n", [element(2, process_info(self(), status))]). queue() -> element(2, process_info(self(), message_queue_len)). drain() -> receive {job, _N} -> drain() after 0 -> ok end.
erlc mailbox.erl
erl -noshell -eval 'mailbox:main(), halt().'
queued: 3 after the drain: 0 status: running
A queue that grows without end is a consumer slower than its senders, and the answer is back pressure rather than a larger mailbox. process_info/2 also answers memory, reductions and current_function, which together say whether a process is busy, blocked or waiting for a message that will never come. The performance lesson measures where the time goes once the queue is healthy.
Tracing a process
erlang:trace/3 turns tracing on for a process, and erlang:trace_pattern/3 decides which calls are reported. The caller becomes the tracer and receives {trace, Pid, call, {Module, Function, Args}} messages in its mailbox, which a program can print, count or store. The program traces one worker and one function:
trace.erl
-module(trace). -export([main/0]). main() -> Self = self(), Pid = spawn(fun() -> receive go -> ok end, Self ! {result, lists:reverse([1, 2, 3])} end), 1 = erlang:trace(Pid, true, [call]), 1 = erlang:trace_pattern({lists, reverse, 1}, true, []), Pid ! go, receive {trace, Pid, call, {Module, Function, Args}} -> io:format("call ~p:~p/~p~n", [Module, Function, length(Args)]) after 1000 -> io:format("no trace message~n") end, receive {result, Reversed} -> io:format("result: ~p~n", [Reversed]) end.
erlc trace.erl
erl -noshell -eval 'trace:main(), halt().'
call lists:reverse/1 result: [3,2,1]
A process cannot trace itself: the runtime keeps the tracer out of its own trace, otherwise the report of a call would produce a call. That is why the worker is a second process and why the trace arrives in the mailbox before the result. In a running system the same two calls are enough to watch a function for a minute, and erlang:trace_pattern/3 accepts a match spec so that only a call with the arguments you care about is reported.
The system monitor
The system monitor sends a message when a process spends too long in the garbage collector or grows a heap past a limit, which is the warning before a node runs out of memory. It is off by default, and the program turns it on and reads the settings back:
system_mon.erl
-module(system_mon). -export([main/0]). main() -> io:format("default: ~p~n", [erlang:system_monitor()]), _ = erlang:system_monitor(self(), [{long_gc, 100}, {large_heap, 1000000}]), Current = erlang:system_monitor(), io:format("options now: ~p~n", [element(2, Current)]), _ = erlang:system_monitor(undefined), io:format("after the reset: ~p~n", [erlang:system_monitor()]).
erlc system_mon.erl
erl -noshell -eval 'system_mon:main(), halt().'
default: undefined options now: [{large_heap,1000000},{long_gc,100}] after the reset: undefined
Only one process at a time receives the monitor messages, and erlang:system_monitor/2 answers the previous settings so that a diagnosis can put them back. The other runtime counters are erlang:statistics/1 for reductions, run queue and wall time, and erlang:memory/0 for the heap, binary and ETS totals. A metric that is sampled on a timer and written to the log is worth more than a dashboard nobody watched during the incident.
The tools without a window
observer is the graphical tool of OTP: it draws the process tree, the memory and the load of a node. It needs a window system and the wx library, and this container has neither, so the page describes it without a screenshot and runs everything else from a shell. observer:start() opens the window on a machine that has one; observer:start() on a release host is a mistake, because a release does not ship the GUI applications.
msacc measures where the runtime spends its time: it samples the scheduler for a period and answers counters for the emulator, the garbage collector, the ports and the lock waits. msacc:start(1000), msacc:stats() and msacc:stop() are the three calls, and the numbers are a map of counters. A node whose lock counters are high has a contention problem in the runtime rather than in the program, which is a different fix. recon is the community library that made these calls convenient, and it is not part of OTP: this environment has no Hex, so the course names it among the packages it cannot fetch.
The order to look at a slow system is the same in every language: check the log for a restart loop, check the mailbox of the process that is slow, trace the call that is expensive, and only then reach for a profiler. Each of the first three needs one call and no build, which is why an Erlang release carries the tools that answer them.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which two places filter a log message by level?
Answer
The primary configuration and the handler
A message passes the primary level and then the level of each handler it reaches.
-
What does a handler of the logger implement?
Answer
log/2The handler receives the level and the message term in
log/2and writes them where it likes. -
What does
process_info(Pid, message_queue_len)answer?Answer
The number of messages waiting
The tuple holds the count of messages the process has not read yet.
-
Why does the tracing program trace a second process?
Answer
Because a process cannot trace itself
The runtime keeps a tracer out of its own trace, so the traced process must be another one.
-
What does
erlang:system_monitor/2answer?Answer
The previous settings
The call returns what was configured before, so a diagnosis can restore it.
-
Why does this page not run
observer?Answer
It needs a window system and wx
The GUI applications need wx and a display, and the container has neither.
-
What does this module print?
-module(q1). -export([main/0]). main() -> ok = logger:set_primary_config(level, warning), logger:info("hidden"), io:format("~p~n", [maps:get(level, logger:get_primary_config())]).Answer
warningThe call set the level to warning, and the configuration reports it back.
-
What does this module print?
-module(q2). -export([main/0]). main() -> Self = self(), [Self ! {job, N} || N <- [1, 2, 3]], io:format("~p~n", [element(2, process_info(self(), message_queue_len))]).Answer
3The three messages are still in the mailbox when the length is read.
-
What does this module print?
-module(q3). -export([main/0]). main() -> Self = self(), Self ! {job, 1}, drain(), io:format("~p~n", [element(2, process_info(self(), message_queue_len))]). drain() -> receive {job, _N} -> drain() after 0 -> ok end.Answer
0The drain consumes the one message, so the mailbox is empty when the length is read.
-
What does this module print?
-module(q4). -export([main/0]). main() -> _ = erlang:system_monitor(self(), [{long_gc, 250}]), io:format("~p~n", [element(2, erlang:system_monitor())]).Answer
[{long_gc,250}]The settings are reported back, and the list holds the one option that was set.
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. The observer was not run: it needs a window system and wx.
Автор статьи: Arthur Isaev