Logging in Erlang
Our first program will demonstrate basic logging functionality in Erlang. Here’s the full source code:
To run the program, save it as logging_example.erl
and use the Erlang shell:
Let’s break down the example:
We start with simple logging using
io:format/1
, which is similar toPrintln
in the original example.We then demonstrate logging with a timestamp. In Erlang, we need to create our own timestamp function.
Custom prefixes are implemented using a helper function
log_with_prefix/2
.For logging to a file, we use Erlang’s built-in file operations.
To demonstrate structured logging, we use the
lager
library, which is commonly used for logging in Erlang applications. Note that you’ll need to add lager as a dependency to your project to use it.The
lager:info/2
function allows us to log both a message and a list of key-value pairs, similar to the structured logging in the original example.
Erlang doesn’t have a direct equivalent to Go’s log
package with flags and prefixes. However, we can achieve similar functionality using a combination of io:format/2
and custom functions.
For more advanced logging needs, consider using established Erlang logging frameworks like lager
or logger
(OTP 21+), which provide more sophisticated features for production environments.