logger(3erl)
πΈ NAME πΈ
logger(3erl) β the API module for Logger, the standard logging facility in Erlang/OTP. Bestie, this is literally the main-character logging API, no cap.
β¨ DESCRIPTION β¨
This module implements the main API for logging in Erlang/OTP. To create a log event, use the API functions or the log macros, for example:
?LOG_ERROR("error happened because: ~p", [Reason]). % With macro
logger:error("error happened because: ~p", [Reason]). % Without macro
To configure the Logger backend, use Kernel configuration parameters or configuration functions in the Logger API.
By default, the Kernel application installs one log handler at system start. This handler is named default. It receives and processes standard log events produced by the Erlang runtime system, standard behaviours and different Erlang/OTP applications. The log events are by default printed to the terminal.
If you want your systems logs to be printed to a file instead, you must configure the default handler to do so. The simplest way is to include the following in your sys.config:
[{kernel,
[{logger,
[{handler, default, logger_std_h,
#{config => #{file => "path/to/file.log"}}}]}]}].
For more information about:
- the Logger facility in general, see the User's Guide.
- how to configure Logger, see the Configuration section in the User's Guide.
- the built-in handlers, see
logger_std_handlogger_disk_log_h. - the built-in formatter, see
logger_formatter. - built-in filters, see
logger_filters.
Note: Since Logger is new in Erlang/OTP 21.0, we do reserve the right to introduce changes to the Logger API and functionality in patches following this release. These changes might or might not be backwards compatible with the initial version.
π§Έ DATA TYPES π§Έ
π§© filter()
filter() =
{fun((log_event(), filter_arg()) -> filter_return()),
filter_arg()}
A filter which can be installed as a handler filter, or as a primary filter in Logger.
π§© filter_arg()
filter_arg() = term()
The second argument to the filter fun.
π§© filter_id()
filter_id() = atom()
A unique identifier for a filter.
π§© filter_return()
filter_return() = stop | ignore | log_event()
The return value from the filter fun.
π§© formatter_config()
formatter_config() = #{atom() => term()}
Configuration data for the formatter. See logger_formatter(3erl) for an example of a formatter implementation.
π§© handler_config()
handler_config() =
#{id => handler_id(),
config => term(),
level => level() | all | none,
module => module(),
filter_default => log | stop,
filters => [{filter_id(), filter()}],
formatter => {module(), formatter_config()}}
Handler configuration data for Logger. The following default values apply:
level => allfilter_default => logfilters => []formatter => {logger_formatter, DefaultFormatterConfig}
In addition to these, the following fields are automatically inserted by Logger, values taken from the two first parameters to add_handler/3:
id => HandlerIdmodule => Module
These are read-only and cannot be changed in runtime.
Handler specific configuration data is inserted by the handler callback itself, in a sub structure associated with the field named config. See the logger_std_h(3erl) and logger_disk_log_h(3erl) manual pages for information about the specific configuration for these handlers.
See the logger_formatter(3erl) manual page for information about the default configuration for this formatter.
π§© handler_id()
handler_id() = atom()
A unique identifier for a handler instance.
π§© level()
level() =
emergency | alert | critical | error | warning | notice |
info | debug
The severity level for the message to be logged.
π§© log_event()
log_event() =
#{level := level(),
msg :=
{io:format(), [term()]} |
{report, report()} |
{string, unicode:chardata()},
meta := metadata()}
π§© metadata()
metadata() =
#{pid => pid(),
gl => pid(),
time => timestamp(),
mfa => {module(), atom(), integer() >= 0},
file => file:filename(),
line => integer() >= 0,
domain => [atom()],
report_cb => report_cb(),
atom() => term()}
Metadata for the log event.
Logger adds the following metadata to each log event:
pid => self()gl => group_leader()time => logger:timestamp()
When a log macro is used, Logger also inserts location information:
mfa => {?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY}file => ?FILEline => ?LINE
You can add custom metadata, either by:
- specifying a map as the last parameter to any of the log macros or the logger API functions.
- setting process metadata with
set_process_metadata/1orupdate_process_metadata/1. - setting primary metadata with
set_primary_config/1or through the kernel configuration parameterlogger_metadata
Note: When adding custom metadata, make sure not to use any of the keys mentioned above as that may cause a lot of confusion about the log events. Logger merges all the metadata maps before forwarding the log event to the handlers. If the same keys occur, values from the log call overwrite process metadata, which overwrites the primary metadata, which in turn overwrite values set by Logger.
The following custom metadata keys have special meaning:
domainβ the value associated with this key is used by filters for grouping log events originating from, for example, specific functional areas. Seelogger_filters:domain/2for a description of how this field can be used.report_cbβ if the log message is specified as areport(), thereport_cbkey can be associated with a fun (report callback) that converts the report to a format string and arguments, or directly to a string. See the type definition ofreport_cb(), and section Log Message in the User's Guide for more information about report callbacks.
π§© msg_fun()
msg_fun() =
fun((term()) ->
msg_fun_return() | {msg_fun_return(), metadata()})
π§© msg_fun_return()
msg_fun_return() =
{io:format(), [term()]} |
report() |
unicode:chardata() |
ignore
π§© olp_config()
olp_config() =
#{sync_mode_qlen => integer() >= 0,
drop_mode_qlen => integer() >= 1,
flush_qlen => integer() >= 1,
burst_limit_enable => boolean(),
burst_limit_max_count => integer() >= 1,
burst_limit_window_time => integer() >= 1,
overload_kill_enable => boolean(),
overload_kill_qlen => integer() >= 1,
overload_kill_mem_size => integer() >= 1,
overload_kill_restart_after => integer() >= 0 | infinity}
π§© primary_config()
primary_config() =
#{level => level() | all | none,
metadata => metadata(),
filter_default => log | stop,
filters => [{filter_id(), filter()}]}
Primary configuration data for Logger. The following default values apply:
level => infofilter_default => logfilters => []
π§© report()
report() = map() | [{atom(), term()}]
π§© report_cb()
report_cb() =
fun((report()) -> {io:format(), [term()]}) |
fun((report(), report_cb_config()) -> unicode:chardata())
A fun which converts a report() to a format string and arguments, or directly to a string. See section Log Message in the User's Guide for more information.
π§© report_cb_config()
report_cb_config() =
#{depth := integer() >= 1 | unlimited,
chars_limit := integer() >= 1 | unlimited,
single_line := boolean()}
π§© timestamp()
timestamp() = integer()
A timestamp produced with logger:timestamp().
π MACROS π
The following macros are defined in logger.hrl, which is included in a module with the directive
-include_lib("kernel/include/logger.hrl").
?LOG_EMERGENCY(StringOrReport[,Metadata])?LOG_EMERGENCY(FunOrFormat,Args[,Metadata])?LOG_ALERT(StringOrReport[,Metadata])?LOG_ALERT(FunOrFormat,Args[,Metadata])?LOG_CRITICAL(StringOrReport[,Metadata])?LOG_CRITICAL(FunOrFormat,Args[,Metadata])?LOG_ERROR(StringOrReport[,Metadata])?LOG_ERROR(FunOrFormat,Args[,Metadata])?LOG_WARNING(StringOrReport[,Metadata])?LOG_WARNING(FunOrFormat,Args[,Metadata])?LOG_NOTICE(StringOrReport[,Metadata])?LOG_NOTICE(FunOrFormat,Args[,Metadata])?LOG_INFO(StringOrReport[,Metadata])?LOG_INFO(FunOrFormat,Args[,Metadata])?LOG_DEBUG(StringOrReport[,Metadata])?LOG_DEBUG(FunOrFormat,Args[,Metadata])?LOG(Level,StringOrReport[,Metadata])?LOG(Level,FunOrFormat,Args[,Metadata])
All macros expand to a call to Logger, where Level is taken from the macro name, or from the first argument in the case of the ?LOG macro. Location data is added to the metadata as described under the metadata() type definition.
The call is wrapped in a case statement and will be evaluated only if Level is equal to or below the configured log level.
π» LOGGING API FUNCTIONS π»
Okay bestie, the actual logging API functions are up next β part 2 picks this up right here, so don't log off yet π
emergency(StringOrReport[,Metadata])emergency(Format,Args[,Metadata])emergency(Fun,FunArgs[,Metadata])
literally just log(emergency,...) bestie, that's the whole thing π
alert(StringOrReport[,Metadata])alert(Format,Args[,Metadata])alert(Fun,FunArgs[,Metadata])
same energy, it's log(alert,...) β¨
critical(StringOrReport[,Metadata])critical(Format,Args[,Metadata])critical(Fun,FunArgs[,Metadata])
yup, log(critical,...) π
error(StringOrReport[,Metadata])error(Format,Args[,Metadata])error(Fun,FunArgs[,Metadata])
you already know: log(error,...) π
warning(StringOrReport[,Metadata])warning(Format,Args[,Metadata])warning(Fun,FunArgs[,Metadata])
log(warning,...) π¦
notice(StringOrReport[,Metadata])notice(Format,Args[,Metadata])notice(Fun,FunArgs[,Metadata])
log(notice,...) πΈ
info(StringOrReport[,Metadata])info(Format,Args[,Metadata])info(Fun,FunArgs[,Metadata])
log(info,...) π«Ά
debug(StringOrReport[,Metadata])debug(Format,Args[,Metadata])debug(Fun,FunArgs[,Metadata])
and yes, log(debug,...) π
π the big one: log π
log(Level, StringOrReport) -> ok
log(Level, StringOrReport, Metadata) -> ok
log(Level, Format, Args) -> ok
log(Level, Fun, FunArgs) -> ok
log(Level, Format, Args, Metadata) -> ok
log(Level, Fun, FunArgs, Metadata) -> ok
Types:
Level = level()
StringOrReport = unicode:chardata() | report()
Format = io:format()
Args = [term()]
Fun = msg_fun()
FunArgs = term()
Metadata = metadata()
okay so this is the function, the main character of the whole page π β it creates a log event at the level you give it, with the message you want logged plus its metadata. Examples, bestie, look:
%% A plain string
logger:log(info, "Hello World").
%% A plain string with metadata
logger:log(debug, "Hello World", #{ meta => data }).
%% A format string with arguments
logger:log(warning, "The roof is on ~ts",[Cause]).
%% A report
logger:log(warning, #{ what => roof, cause => Cause }).
Now here's the cute part π§ β the message and metadata can either be handed to you directly in the arguments, or they can come back from a fun. Passing a fun instead of the message/metadata directly is genuinely useful when the message/metadata is very expensive to compute, because the fun is only evaluated when the message/metadata is actually needed β which might be, like, not at all if the log event isn't going to be logged. Work smarter not harder fr fr π Examples:
%% A plain string with expensive metadata
logger:info(fun([]) -> {"Hello World", #{ meta => expensive() }} end,[]).
%% An expensive report
logger:debug(fun(What) -> #{ what => What, cause => expensive() } end,roof).
%% A plain string with expensive metadata and normal metadata
logger:debug(fun([]) -> {"Hello World", #{ meta => expensive() }} end,[],
#{ meta => data }).
β οΈ when metadata is given both as an argument and returned from the fun, they get merged. If equal keys exist, the values are taken from the metadata returned by the fun. no cap, the fun wins π
βοΈ CONFIGURATION API FUNCTIONS βοΈ
EXPORTS
π§© add_handler(HandlerId, Module, Config) -> ok | {error, term()}
Types:
HandlerId = handler_id()
Module = module()
Config = handler_config()
Adds a handler with the given configuration. π
HandlerId is a unique identifier, and bestie you must use it in all subsequent calls that refer to this handler. It's the handler's whole name, its whole identity, its main character energy π
π add_handler_filter(HandlerId, FilterId, Filter) -> ok | {error, term()}
Types:
HandlerId = handler_id()
FilterId = filter_id()
Filter = filter()
Adds a filter to the specified handler. π
The filter fun gets called with the log event as the first parameter, and the specified filter_args() as the second parameter.
The return value of the fun is what decides whether a log event gets discarded or forwarded to the handler callback:
log_event():β the filter passed! The next handler filter, if any, gets applied. And if there are no more filters for this handler, the log event is forwarded to the handler callback. slay β¨stop:β the filter did not pass, and the log event is immediately discarded. bye πignore:β the filter has no knowledge of the log event. The next handler filter, if any, gets applied. And if there are no more filters for this handler, the value of thefilter_defaultconfiguration parameter for the handler decides whether the log event shall be discarded or forwarded to the handler callback. π€·βοΈ
See section Filters in the User's Guide for more info about filters.
Some built-in filters exist, and they're defined in logger_filters(3erl). π¦
π add_handlers(Application) -> ok | {error, term()}
Types:
Application = atom()
Reads the application configuration parameter logger and calls add_handlers/1 with its contents.
π add_handlers(HandlerConfig) -> ok | {error, term()}
Types:
HandlerConfig = [config_handler()]
config_handler() =
{handler, handler_id(), module(), handler_config()}
This one should be used by custom Logger handlers so the configuration stays consistent no matter which handler the system uses. π
Normal usage: add a call to logger:add_handlers/1 just after the processes that the handler needs are started, and pass the application's logger configuration as the argument. For example:
-behaviour(application).
start(_, []) ->
case supervisor:start_link({local, my_sup}, my_sup, []) of
{ok, Pid} ->
ok = logger:add_handlers(my_app),
{ok, Pid, []};
Error -> Error
end.
This reads the logger configuration parameter from the my_app application and starts the configured handlers. The contents of the configuration use the same rules as the logger handler configuration.
π¨ If the handler is meant to replace the default handler, the Kernel's default handler has to be disabled before the new handler is added. A sys.config file that disables the Kernel handler and adds a custom handler could look like this:
[{kernel,
[{logger,
%% Disable the default Kernel handler
[{handler, default, undefined}]}]},
{my_app,
[{logger,
%% Enable this handler as the default
[{handler, default, my_handler, #{}}]}]}].
π₯ add_primary_filter(FilterId, Filter) -> ok | {error, term()}
Types:
FilterId = filter_id()
Filter = filter()
Adds a primary filter to Logger. π
The filter fun gets called with the log event as the first parameter, and the specified filter_args() as the second parameter.
The return value of the fun decides whether a log event gets discarded or forwarded to the handlers:
log_event():β the filter passed! The next primary filter, if any, gets applied. And if there are no more primary filters, the log event is forwarded to the handler part of Logger, where handler filters are applied. πstop:β the filter did not pass, and the log event is immediately discarded. gone, reduced to atoms πignore:β the filter has no knowledge of the log event. The next primary filter, if any, gets applied. And if there are no more primary filters, the value of the primaryfilter_defaultconfiguration parameter decides whether the log event shall be discarded or forwarded to the handler part. π€·βοΈ
See section Filters in the User's Guide for more info about filters.
Some built-in filters exist, and they're defined in logger_filters(3erl). πΈ
π get_config() β the whole vibe check
get_config() ->
#{primary => primary_config(),
handlers => [handler_config()],
proxy => olp_config(),
module_levels =>
[{module(), level() | all | none}]}
Looks up all current Logger configuration, including primary, handler, and proxy configuration, and module level settings. it's giving full transparency π
π get_handler_config() -> [Config]
Types:
Config = handler_config()
Looks up the current configuration for all handlers.
π get_handler_config(HandlerId) -> {ok, Config} | {error, term()}
Types:
HandlerId = handler_id()
Config = handler_config()
Looks up the current configuration for the given handler.
πͺͺ get_handler_ids() -> [HandlerId]
Types:
HandlerId = handler_id()
Looks up the identities for all installed handlers. π«Ά
π get_primary_config() -> Config
Types:
Config = primary_config()
Looks up the current primary configuration for Logger.
π get_proxy_config() -> Config
Types:
Config = olp_config()
Looks up the current configuration for the Logger proxy.
For more info about the proxy, see section Logger Proxy in the Kernel User's Guide. π¦
π·οΈ get_module_level() -> [{Module, Level}]
Types:
Module = module()
Level = level() | all | none
Looks up all current module levels. Returns a list containing one {Module,Level} element for each module for which the module level was previously set with set_module_level/2. β¨
π·οΈ get_module_level(Modules) -> [{Module, Level}]
Types:
Modules = [Module] | Module
Module = module()
Level = level() | all | none
Looks up the current level for the given modules. Returns a list containing one {Module,Level} element for each of the given modules for which the module level was previously set with set_module_level/2. π
π§ get_process_metadata() -> Meta | undefined
Types:
Meta = metadata()
Retrieves data set with set_process_metadata/1 or update_process_metadata/1. it remembers what you told it, bestie π
π₯οΈ i() -> ok
π₯οΈ i(What) -> ok
Types:
What = primary | handlers | proxy | modules | handler_id()
no cap, that's the whole signature list π
This next one is a total vibe check for your setup: it pretty prints the Logger configuration. β¨
remove_handler(HandlerId) -> ok | {error, term()}
Types:
HandlerId = handler_id()
Okay so this one removes the handler identified by HandlerId. Bye-bye, handler β itβs giving cleanup era. π§Ή
remove_handler_filter(HandlerId, FilterId) -> ok | {error, term()}
Types:
HandlerId = handler_id()
FilterId = filter_id()
This plucks the filter identified by FilterId out of the handler identified by HandlerId. No cap, very surgical. π
remove_primary_filter(FilterId) -> ok | {error, term()}
Types:
FilterId = filter_id()
This removes the primary filter identified by FilterId from Logger. Primary filter said βnot today.β π«Ά
set_application_level(Application, Level) -> ok | {error, not_loaded}
Types:
Application = atom()
Level = level() | all | none
Set the log level for all the modules of the specified application. This is a convenience function that calls logger:set_module_level/2 for each module associated with an application. Itβs literally a little level-setting tour for the whole app. π
set_handler_config(HandlerId, Config) -> ok | {error, term()}
Types:
HandlerId = handler_id()
Config = handler_config()
Set configuration data for the specified handler. This overwrites the current handler configuration. Like, full reset energy. π
To modify the existing configuration, use update_handler_config/2, or, if a more complex merge is needed, read the current configuration with get_handler_config/1, then do the merge before writing the new configuration back with this function.
If a key is removed compared to the current configuration, and the key is known by Logger, the default value is used. If it is a custom key, then it is up to the handler implementation if the value is removed or a default value is inserted. Custom-key behavior is lowkey the handlerβs business, not Loggerβs. π
set_handler_config(HandlerId, Key :: level, Level) -> Return set_handler_config(HandlerId, Key :: filter_default, FilterDefault) -> Return set_handler_config(HandlerId, Key :: filters, Filters) -> Return set_handler_config(HandlerId, Key :: formatter, Formatter) -> Return set_handler_config(HandlerId, Key :: config, Config) -> Return
Types:
HandlerId = handler_id()
Level = level() | all | none
FilterDefault = log | stop
Filters = [{filter_id(), filter()}]
Formatter = {module(), formatter_config()}
Config = term()
Return = ok | {error, term()}
Add or update configuration data for the specified handler. If the given Key already exists, its associated value will be changed to the given value. If it does not exist, it will be added. Very glow-up, very βwe update around here.β β¨
If the value is incomplete, which for example can be the case for the config key, it is up to the handler implementation how the unspecified parts are set. For all handlers in the Kernel application, unspecified data for the config key is set to default values. To update only specified data, and keep the existing configuration for the rest, use update_handler_config/3.
See the definition of the handler_config() type for more information about the different parameters. Itβs giving βread the docs for the lore.β π
set_primary_config(Config) -> ok | {error, term()}
Types:
Config = primary_config()
Set primary configuration data for Logger. This overwrites the current configuration. Full main-character rewrite. π
To modify the existing configuration, use update_primary_config/1, or, if a more complex merge is needed, read the current configuration with get_primary_config/0, then do the merge before writing the new configuration back with this function.
If a key is removed compared to the current configuration, the default value is used. Defaults said βIβm still here, bestie.β πΈ
set_primary_config(Key :: level, Level) -> ok | {error, term()} set_primary_config(Key :: filter_default, FilterDefault) -> ok | {error, term()} set_primary_config(Key :: filters, Filters) -> ok | {error, term()} set_primary_config(Key :: metadata, Meta) -> ok | {error, term()}
Types:
Level = level() | all | none
FilterDefault = log | stop
Filters = [{filter_id(), filter()}]
Meta = metadata()
Add or update primary configuration data for Logger. If the given Key already exists, its associated value will be changed to the given value. If it does not exist, it will be added. Simple as that, fr fr. π¦
set_proxy_config(Config) -> ok | {error, term()}
Types:
Config = olp_config()
Set configuration data for the Logger proxy. This overwrites the current proxy configuration. Keys that are not specified in the Config map get default values.
To modify the existing configuration, use update_proxy_config/1, or, if a more complex merge is needed, read the current configuration with get_proxy_config/0, then do the merge before writing the new configuration back with this function.
For more information about the proxy, see section Logger Proxy in the Kernel Userβs Guide. Proxy lore is real. π§
set_module_level(Modules, Level) -> ok | {error, term()}
Types:
Modules = [module()] | module()
Level = level() | all | none
Set the log level for the specified modules. This is where things get spicy. π₯
The log level for a module overrides the primary log level of Logger for log events originating from the module in question. Notice, however, that it does not override the level configuration for any handler. So itβs not out here overriding handler business. Periodt.
For example: Assume that the primary log level for Logger is info, and there is one handler, h1, with level info and one handler, h2, with level debug.
With this configuration, no debug messages will be logged, since they are all stopped by the primary log level.
If the level for mymodule is now set to debug, then debug events from this module will be logged by the handler h2, but not by handler h1.
Debug events from other modules are still not logged. Other modules said βweβre not on that level.β π
To change the primary log level for Logger, use set_primary_config(level, Level).
To change the log level for a handler, use set_handler_config(HandlerId, level, Level).
Note: The originating module for a log event is only detected if the keymfaexists in the metadata, and is associated with{Module, Function, Arity}. When log macros are used, this association is automatically added to all log events. If an API function is called directly, without using a macro, the logging client must explicitly add this information if module levels shall have any effect. Ngl, this is the βiykykβ of module levels. π
set_process_metadata(Meta) -> ok
Types:
Meta = metadata()
Set metadata which Logger shall automatically insert in all log events produced on the current process. Process metadata said βIβm coming with you everywhere.β π«Ά
Location data produced by the log macros, and/or metadata given as argument to the log call (API function or macro), are merged with the process metadata. If the same keys occur, values from the metadata argument to the log call overwrite values from the process metadata, which in turn overwrite values from the location data.
Subsequent calls to this function overwrites previous data set. To update existing data instead of overwriting it, see update_process_metadata/1. Donβt overwrite by accident, bestie. π
unset_application_level(Application) -> ok | {error, {not_loaded, Application}}
Types:
Application = atom()
Unset the log level for all the modules of the specified application.
This function is a utility function that calls logger:unset_module_level/2 for each module associated with an application. Group cleanup, but make it application-wide. π§Ή
unset_module_level() -> ok
Remove module specific log settings. After this, the primary log level is used for all modules. Back to default vibes. π
unset_module_level(Modules) -> ok
Types:
Modules = [module()] | module()
Remove module specific log settings. After this, the primary log level is used for the specified modules. Only the listed modules get their settings yeeted. π
unset_process_metadata() -> ok
Delete data set with set_process_metadata/1 or update_process_metadata/1. Process metadata? Never heard of her. π
update_formatter_config(HandlerId, FormatterConfig) -> ok | {error, term()}
Types:
HandlerId = handler_id()
FormatterConfig = formatter_config()
Update the formatter configuration for the specified handler.
The new configuration is merged with the existing formatter configuration. Very merge, very mindful. β¨
To overwrite the existing configuration without any merge, use
set_handler_config(HandlerId, formatter, {FormatterModule, FormatterConfig}).
update_formatter_config(HandlerId, Key, Value) -> ok | {error, term()}
Types:
HandlerId = handler_id()
Key = atom()
Value = term()
Update the formatter configuration for the specified handler.
This is equivalent to
update_formatter_config(HandlerId, #{Key => Value})
update_handler_config(HandlerId, Config) -> ok | {error, term()}
Types:
HandlerId = handler_id()
Config = handler_config()
Update configuration data for the specified handler. This function behaves as if it was implemented as follows:
{ok, {_, Old}} = logger:get_handler_config(HandlerId),
logger:set_handler_config(HandlerId, maps:merge(Old, Config)).
To overwrite the existing configuration without any merge, use set_handler_config/2. Merge responsibly, bestie. π¦
update_handler_config(HandlerId, Key :: level, Level) -> Return update_handler_config(HandlerId, Key :: filter_default, FilterDefault) -> Return update_handler_config(HandlerId, Key :: filters, Filters) -> Return update_handler_config(HandlerId, Key :: formatter, Formatter) -> Return update_handler_config(HandlerId, Key :: config, Config) -> Return
Types:
Okay bestie, we're still in the update_handler_config/3 zone π
β here's the rest of the types, then the tea:
HandlerId = handler_id()
Level = level() | all | none
FilterDefault = log | stop
Filters = [{filter_id(), filter()}]
Formatter = {module(), formatter_config()}
Config = term()
Return = ok | {error, term()}
This one adds or updates config data for the handler you picked. If the Key you passed already exists, its value gets swapped for the new value. If it does not exist yet, it gets added. No cap.
If the value is incomplete β like, say, for the config key β it's up to the handler implementation how the unspecified parts get set. For every handler in the Kernel application, unspecified data for the config key stays exactly as it was. Wanna reset unspecified data to default values? Use set_handler_config/3 instead. Periodt.
For more info on the different parameters, see the definition of the handler_config() type. π
update_primary_config(Config) -> ok | {error, term()}
Types:
Config = primary_config()
Updates the primary config for Logger. It's literally the same as running this:
Old = logger:get_primary_config(),
logger:set_primary_config(maps:merge(Old, Config)).
If you want to overwrite the existing config with zero merging, use set_primary_config/1. Simple.
update_process_metadata(Meta) -> ok
Types:
Meta = metadata()
Sets or updates metadata to use when logging from the current process.
If process metadata already exists for the current process, this function behaves exactly like this:
logger:set_process_metadata(maps:merge(logger:get_process_metadata(), Meta)).
If no process metadata exists, it behaves like set_process_metadata/1. That's the whole vibe.
update_proxy_config(Config) -> ok | {error, term()}
Types:
Config = olp_config()
Updates config data for the Logger proxy. Behaves exactly like this:
Old = logger:get_proxy_config(),
logger:set_proxy_config(maps:merge(Old, Config)).
To overwrite without any merge, use set_proxy_config/1. For more proxy lore, see section Logger Proxy in the Kernel User's Guide. π
β¨ MISCELLANEOUS API FUNCTIONS β¨
EXPORTS
compare_levels(Level1, Level2) -> eq | gt | lt
Types:
Level1 = Level2 = level() | all | none
Compares the severity of two log levels. Returns gt if Level1 is more severe than Level2, lt if Level1 is less severe, and eq if the levels are equal. It's giving level hierarchy realness.
format_report(Report) -> FormatArgs
Types:
Report = report()
FormatArgs = {io:format(), [term()]}
Converts a log message on report form to {Format, Args}. This is the default report callback that logger_formatter(3erl) uses when no custom report callback is found. See section Log Message in the Kernel User's Guide for the full tea on report callbacks and valid forms of log messages.
The function produces lines of Key: Value from key-value lists. Strings are printed with ~ts, and other terms are printed with ~tp.
If Report is a map, it gets converted to a key-value list before being formatted as such. Obsessed.
timestamp() -> timestamp()
Returns a timestamp that can be inserted as the time field in the meta data for a log event. It is produced with os:system_time(microsecond).
Notice that Logger automatically inserts a timestamp in the meta data unless it already exists. This function is exported for the rare case when the timestamp must be taken at a different point in time than when the log event is issued. Rare but iconic.
reconfigure() -> ok | {error, term()}
Reconfigures Logger using updated kernel configuration that was set after the kernel application was loaded.
Beware bestie: this is meant to be run only by the build tools, not manually during application lifetime, as this may cause missing log entries. Do not casually vibe-check this one in production. π
π«Ά HANDLER CALLBACK FUNCTIONS π«Ά
The following functions are to be exported from a handler callback module. So if you're writing a handler, these are the callbacks you gotta know.
EXPORTS
HModule:adding_handler(Config1) -> {ok, Config2} | {error, Reason}
Types:
Config1 = Config2 = handler_config()
Reason = term()
This callback function is optional.
The function is called on a temporary process when a new handler is about to be added. The purpose is to verify the configuration and initiate all resources needed by the handler.
The handler identity is associated with the id key in Config1.
If everything succeeds, the callback function can add possible default values or internal state values to the configuration, and return the adjusted map in {ok,Config2}.
If the configuration is faulty, or if the initiation fails, the callback function must return {error,Reason}. No exceptions.
HModule:changing_config(SetOrUpdate, OldConfig, NewConfig) -> {ok, Config} | {error, Reason}
Types:
SetOrUpdate = set | update
OldConfig = NewConfig = Config = handler_config()
Reason = term()
This callback function is optional.
The function is called on a temporary process when the configuration for a handler is about to change. The purpose is to verify and act on the new configuration.
OldConfig is the existing configuration and NewConfig is the new configuration.
The handler identity is associated with the id key in OldConfig.
SetOrUpdate has the value set if the configuration change originates from a call to set_handler_config/2,3, and update if it originates from update_handler_config/2,3. The handler can use this parameter to decide how to update the value of the config field β that is, the handler-specific configuration data, iykyk. Typically, if SetOrUpdate equals set, values that are not specified must be given their default values. If SetOrUpdate equals update, the values found in OldConfig must be used instead.
If everything succeeds, the callback function must return a possibly adjusted configuration in {ok,Config}.
If the configuration is faulty, the callback function must return {error,Reason}.
HModule:filter_config(Config) -> FilteredConfig
Types:
Config = FilteredConfig = handler_config()
This callback function is optional.
The function is called when one of the Logger API functions for fetching the handler configuration is called, for example logger:get_handler_config/1.
It allows the handler to remove internal data fields from its configuration data before it is returned to the caller. Cute.
HModule:log(LogEvent, Config) -> void()
Types:
LogEvent = log_event()
Config = handler_config()
This callback function is mandatory, bestie.
The function is called when all primary filters and all handler filters for the handler in question have passed for the given log event. It is called on the client process, that is, the process that issued the log event.
The handler identity is associated with the id key in Config.
The handler must log the event.
The return value from this function is ignored by Logger. That's it.
HModule:removing_handler(Config) -> ok
Types:
Config = handler_config()
This callback function is optional.
The function is called on a temporary process when a handler is about to be removed. The purpose is to release all resources used by the handler.
The handler identity is associated with the id key in Config.
The return value is ignored by Logger.
π FORMATTER CALLBACK FUNCTIONS π
The following functions are to be exported from a formatter callback module. If you're making a formatter, these are your callbacks.
EXPORTS
FModule:check_config(FConfig) -> ok | {error, Reason}
Types:
FConfig = formatter_config()
Reason = term()
This callback function is optional.
The function is called by a Logger when formatter configuration is set or modified. The formatter must validate the given configuration and return ok if it is correct, and {error,Reason} if it is faulty.
The following Logger API functions can trigger this callback:
logger:add_handler/3logger:set_handler_config/2,3logger:update_handler_config/2,3logger:update_formatter_config/2
See logger_formatter(3erl) for an example implementation. logger_formatter is the default formatter used by Logger. Slay.
FModule:format(LogEvent, FConfig) -> FormattedLogEntry
Types:
LogEvent = log_event()
FConfig = formatter_config()
FormattedLogEntry = unicode:chardata()
This callback function is mandatory.
The function can be called by a log handler to convert a log event term to a printable string. The returned value can, for example, be printed as a log entry to the console or a file using io:put_chars/1,2.
See logger_formatter(3erl) for an example implementation. logger_formatter is the default formatter used by Logger.
π¦ SEE ALSO π¦
Check out these other pages, bestie:
config(5)erlang(3erl)io(3erl)logger_disk_log_h(3erl)logger_filters(3erl)logger_formatter(3erl)logger_std_h(3erl)unicode(3erl)
That's the whole logger(3erl) page from Ericsson AB, kernel 8.5.4.2 β mwah πβ¨ We're done, bestie π«Άπ
π¦ where this page comes from
- ubuntu noble: erlang-manpages 1:25.3.2.8+dfsg-1ubuntu4 Β· Apache-2.0
- ubuntu noble: erlang-manpages 1:25.3.2.8+dfsg-1ubuntu4.8 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms