logger(3)

πŸ“¦
version 29.0.6 Β· 3 versions
, in ubuntu stonking

✨ NAME ✨

logger β€” API module for Logger, the standard logging facility in Erlang/OTP. πŸ’–

πŸ’– DESCRIPTION πŸ’–

okay bestie, so this module is literally THE main API for logging in Erlang/OTP. To create a log event, you use the API functions or the log macros, like:

?LOG_ERROR("error happened because: ~p", [Reason]).   % With macro
logger:error("error happened because: ~p", [Reason]). % Without macro

To configure the Logger backend, you use Kernel configuration parameters or configuration functions in the logger API. No cap. πŸ’…

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 system's 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_h and logger_disk_log_h.
  • the built-in formatter, see logger_formatter.
  • built-in filters, see logger_filters.

✨ 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/0 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.

🌈 See Also 🌈

config, erlang, io, logger_disk_log_h, logger_filters, logger_handler, logger_formatter, logger_std_h, unicode


πŸ¦‹ DATA TYPES πŸ¦‹

  • config_handler()
config_handler() ::
          {handler,
           logger_handler:id(),
           module(),
           logger_handler:config()}.

Configuration used when adding or updating a handler.

  • 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() β€” term(). The second argument to the filter fun.
  • filter_id() β€” atom(). A unique identifier for a filter.
  • filter_return() β€” stop | ignore | log_event(). The return value from the filter fun.
  • formatter_config() β€” #{atom() => term()}. Configuration data for the formatter. See logger_formatter for an example of a formatter implementation.
  • handler_config() β€” logger_handler:config(). Handler configuration data for Logger.
NOTE: DEPRECATED: Use logger_handler:config/0 instead.
  • handler_id() β€” logger_handler:id(). A unique identifier for a handler instance.
NOTE: DEPRECATED: Use logger_handler:id/0 instead.
  • 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()}.

A log event passed to filters and handlers

  • metadata()
metadata() ::
          #{pid => pid(),
            gl => pid(),
            time => timestamp(),
            mfa => {module(), atom(), non_neg_integer()},
            file => file:filename(),
            line => non_neg_integer(),
            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 => ?FILE
  • line => ?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/1 or update_process_metadata/1.
  • setting primary metadata with set_primary_config/1 or through the kernel configuration parameter logger_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. See logger_filters:domain/2 for a description of how this field can be used.
  • report_cb β€” If the log message is specified as a report/0, the report_cb key 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 of report_cb/0, 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() β€” logger_handler:olp_config(). Overload protection configuration.
NOTE: DEPRECATED: Use logger_handler:olp_config/0 instead.
  • 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 => info
  • filter_default => log
  • filters => []
  • report() β€” map() | [{atom(), term()}, ...]. A log report.
  • 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 := pos_integer() | unlimited,
            chars_limit := pos_integer() | unlimited,
            single_line := boolean()}.
  • timestamp() β€” integer(). A timestamp produced with logger:timestamp().

πŸ’… FUNCTIONS πŸ’…

  • add_handler(HandlerId, Module, Config) -> ok | {error, term()}
add_handler(HandlerId, Module, Config) -> ok | {error, term()}
                     when
                         HandlerId :: logger_handler:id(),
                         Module :: module(),
                         Config :: logger_handler:config().

Add a handler with the given configuration.

HandlerId is a unique identifier which must be used in all subsequent calls referring to this handler.

  • add_handler_filter(HandlerId, FilterId, Filter) -> ok | {error, term()}
add_handler_filter(HandlerId, FilterId, Filter) ->
                            ok | {error, term()}
                            when
                                HandlerId :: logger_handler:id(),
                                FilterId :: filter_id(),
                                Filter :: filter().

Add a filter to the specified handler.

The filter fun is called with the log event as the first parameter, and the specified filter_args() as the second parameter.

The return value of the fun specifies if a log event is to be discarded or forwarded to the handler callback:

  • log_event/0 β€” The filter passed. The next handler filter, if any, is applied. If no more filters exist for this handler, the log event is forwarded to the handler callback.
  • stop β€” The filter did not pass, and the log event is immediately discarded.
  • ignore β€” The filter has no knowledge of the log event. The next handler filter, if any, is applied. If no more filters exist for this handler, the value of the filter_default configuration parameter for the handler specifies if the log event shall be discarded or forwarded to the handler callback.

See section Filters in the User's Guide for more information about filters.

Some built-in filters exist. These are defined in logger_filters.

  • add_handlers(Application) -> ok | {error, term()}
add_handlers(Application) -> ok | {error, term()}
                     when Application :: atom();
                 (HandlerConfig) -> ok | {error, term()}
                     when HandlerConfig :: [config_handler()].

Okay so, continuing β€” this one reads the application configuration parameter logger and calls add_handlers/1 with its contents. πŸ’–

This function should be used by custom Logger handlers to make configuration consistent no matter which handler the system uses. Normal usage is to 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 have 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/2 πŸŽ€

add_primary_filter(FilterId, Filter) -> ok | {error, term()}
                            when
                                FilterId :: filter_id(),
                                Filter :: filter().

Add a primary filter to Logger. slay. ✨

The filter fun is called with the log event as the first parameter, and the specified filter_args() as the second parameter.

The return value of the fun specifies if a log event is to be discarded or forwarded to the handlers:

  • log_event/0 β€” the filter passed, bestie 🫢. The next primary filter, if any, is applied. If no more primary filters exist, 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, no notes.
  • ignore β€” the filter has no knowledge of the log event. The next primary filter, if any, is applied. If no more primary filters exist, the value of the primary filter_default configuration parameter specifies if the log event shall be discarded or forwarded to the handler part.

See section Filters in the User's Guide for more information about filters.

Some built-in filters exist. These are defined in logger_filters. πŸ‘‘

alert/2 🌸

alert(String :: unicode:chardata(), Metadata :: metadata()) -> ok;
         (Report :: report(), Metadata :: metadata()) -> ok;
         (Format :: io:format(), Args :: [term()]) -> ok;
         (Fun :: msg_fun(), FunArgs :: term()) -> ok.

Create a alert log event. ✨

Equivalent to log(alert, StringOrReport, Metadata) if called as alert(StringOrReport, Metadata).

Equivalent to alert(FormatOrFun, Args, #{}) if called as alert(FormatOrFun, Args).

compare_levels/2 βš–οΈ

compare_levels(Level1, Level2) -> eq | gt | lt
                        when
                            Level1 :: level() | all | none,
                            Level2 :: level() | all | none.

Compare 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. vibe check, but for severities πŸ’…

critical/2 πŸ”₯

critical(String :: unicode:chardata(), Metadata :: metadata()) ->
                  ok;
              (Report :: report(), Metadata :: metadata()) -> ok;
              (Format :: io:format(), Args :: [term()]) -> ok;
              (Fun :: msg_fun(), FunArgs :: term()) -> ok.

Create a critical log event. 😭

Equivalent to log(critical, StringOrReport, Metadata) if called as critical(StringOrReport, Metadata).

Equivalent to critical(FormatOrFun, Args, #{}) if called as critical(FormatOrFun, Args).

debug/2 πŸ¦‹

debug(String :: unicode:chardata(), Metadata :: metadata()) -> ok;
         (Report :: report(), Metadata :: metadata()) -> ok;
         (Format :: io:format(), Args :: [term()]) -> ok;
         (Fun :: msg_fun(), FunArgs :: term()) -> ok.

Create a debug log event. πŸ›

Equivalent to log(debug, StringOrReport, Metadata) if called as debug(StringOrReport, Metadata).

Equivalent to debug(FormatOrFun, Args, #{}) if called as debug(FormatOrFun, Args).

emergency/2 🚨

emergency(String :: unicode:chardata(), Metadata :: metadata()) ->
                     ok;
                 (Report :: report(), Metadata :: metadata()) -> ok;
                 (Format :: io:format(), Args :: [term()]) -> ok;
                 (Fun :: msg_fun(), FunArgs :: term()) -> ok.

Create a emergency log event. the most main character of all the levels fr fr πŸ‘‘

Equivalent to log(emergency, StringOrReport, Metadata) if called as emergency(StringOrReport, Metadata).

Equivalent to emergency(FormatOrFun, Args, #{}) if called as emergency(FormatOrFun, Args).

error/2 πŸ’€

error(String :: unicode:chardata(), Metadata :: metadata()) -> ok;
         (Report :: report(), Metadata :: metadata()) -> ok;
         (Format :: io:format(), Args :: [term()]) -> ok;
         (Fun :: msg_fun(), FunArgs :: term()) -> ok.

Create a error log event. πŸ™ˆ

Equivalent to log(error, StringOrReport, Metadata) if called as error(StringOrReport, Metadata).

Equivalent to error(FormatOrFun, Args, #{}) if called as error(FormatOrFun, Args).

format_report/1 πŸŽ€

format_report(Report) -> FormatArgs
                       when
                           Report :: report(),
                           FormatArgs :: {io:format(), [term()]}.

Convert a log message on report form to {Format, Args}. This is the default report callback used by logger_formatter when no custom report callback is found. See section Log Message in the Kernel User's Guide for information about 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 with ~tp.

If Report is a map, it is converted to a key-value list before formatting as such. ✨

get_config/0 🌈

get_config() ->
                    #{primary => primary_config(),
                      handlers => [logger_handler:config()],
                      proxy => olp_config(),
                      module_levels =>
                          [{module(), level() | all | none}]}.

Look up all current Logger configuration, including primary, handler, and proxy configuration, and module level settings. the whole entire vibe, in one map πŸ’–

get_handler_config/0 πŸ“

get_handler_config() -> [Config]
                            when Config :: logger_handler:config().

Look up the current configuration for all handlers.

get_handler_config/1 🌸

get_handler_config(HandlerId) -> {ok, Config} | {error, term()}
                            when
                                HandlerId :: logger_handler:id(),
                                Config :: logger_handler:config().

Look up the current configuration for the given handler. 🫢

get_handler_ids/0 πŸ‘‘

get_handler_ids() -> [HandlerId]
                         when HandlerId :: logger_handler:id().

Look up the identities for all installed handlers. pretty iconic tbh ✨

get_module_level/0 🧚

get_module_level() -> [{Module, Level}]
                          when
                              Module :: module(),
                              Level :: level() | all | none.

Look 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/1 🧚

get_module_level(Modules) -> [{Module, Level}]
                          when
                              Modules :: [Module] | Module,
                              Module :: module(),
                              Level :: level() | all | none.

Look 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_primary_config/0 🌟

get_primary_config() -> Config when Config :: primary_config().

Look up the current primary configuration for Logger.

get_process_metadata/0 πŸŽ€

get_process_metadata() -> Meta | undefined when Meta :: metadata().

Retrieve data set with set_process_metadata/1 or update_process_metadata/1. 🫢

get_proxy_config/0 πŸ¦‹

get_proxy_config() -> Config when Config :: olp_config().

Look up the current configuration for the Logger proxy. 🌸

For more information about the proxy, see section Logger Proxy in the Kernel User's Guide.

i/0 πŸ’…

i() -> ok.

Pretty print all Logger configuration. aesthetic printing, literally ✨

i/1 πŸ’…

i(What) -> ok
           when
               What ::
                   primary | handlers | proxy | modules |
                   logger_handler:id().

Pretty print the Logger configuration. πŸ‘‘

info/2 🌈

info(String :: unicode:chardata(), Metadata :: metadata()) -> ok;
        (Report :: report(), Metadata :: metadata()) -> ok;
        (Format :: io:format(), Args :: [term()]) -> ok;
        (Fun :: msg_fun(), FunArgs :: term()) -> ok.

Create a info log event. πŸ¦‹

Equivalent to log(info, StringOrReport, Metadata) if called as info(StringOrReport, Metadata).

Equivalent to info(FormatOrFun, Args, #{}) if called as info(FormatOrFun, Args).

log/3 πŸ”₯

log(Level :: level(),
          String :: unicode:chardata(),
          Metadata :: metadata()) ->
             ok;
         (Level :: level(), Report :: report(), Metadata :: metadata())
->
             ok;
         (Level :: level(), Format :: io:format(), Args :: [term()]) ->
             ok;
         (Level :: level(), Fun :: msg_fun(), FunArgs :: term()) -> ok.

Create a log event at the given log level, with the given message to be logged and metadata. the big one, the legend, the blueprint πŸ’–

Example:

%% A plain string
1> logger:log(info, "Hello World").
%% A plain string with metadata
2> logger:log(debug, "Hello World", #{ meta => data }).
%% A format string with arguments
3> logger:log(warning, "The roof is on ~ts",[Cause]).
%% A report
4> logger:log(warning, #{ what => roof, cause => Cause }).

Basically it's the exact same thing as log(Level, FormatOrFun, Args, #{}) when u call it the short way, log(Level, FormatOrFun, Args). πŸ’…


🫢 log/4 🫢

log(Level :: level(),
    Format :: io:format(),
    Args :: [term()],
    Metadata :: metadata()) ->
       ok;
   (Level :: level(),
    Fun :: msg_fun(),
    FunArgs :: term(),
    Metadata :: metadata()) ->
       ok.

bestie. this one spins up a log event at whatever log level u hand it, with the message u wanna log AND the metadata. ✨

okay so here's the cute part: the message and the metadata can either come straight from the arguments, or they can be returned from a fun. and like… why would u ever pass a fun? because sometimes computing the message/metadata is SO expensive and ur not trying to pay that cost for a log event that's gonna get dropped anyway. the fun only gets evaluated when the message/metadata is actually needed β€” which, lowkey, might be never if the log event isn't getting logged at all. πŸ’€

examples, bestie:

%% A plain string with expensive metadata
1> logger:info(fun([]) -> {"Hello World", #{ meta => expensive() }} end,[]).
%% An expensive report
2> logger:debug(fun(What) -> #{ what => What, cause => expensive() } end,roof).
%% A plain string with expensive metadata and normal metadata
3> logger:debug(fun([]) -> {"Hello World", #{ meta => expensive() }} end,[],
                #{ meta => data }).

and when metadata shows up both as an argument and from the fun? they get merged, no drama. and if there's an equal key in both places, the value comes from the metadata the fun returned. the fun wins, periodt. πŸ‘‘

🌸 notice/2 🌸

notice(String :: unicode:chardata(), Metadata :: metadata()) -> ok;
       (Report :: report(), Metadata :: metadata()) -> ok;
       (Format :: io:format(), Args :: [term()]) -> ok;
       (Fun :: msg_fun(), FunArgs :: term()) -> ok.

makes u a notice log event. that's it, that's the vibe. ✨

  • if u call it as notice(StringOrReport, Metadata), it's equivalent to log(notice, StringOrReport, Metadata).
  • if u call it as notice(FormatOrFun, Args), it's equivalent to notice(FormatOrFun, Args, #{}).

🧚 reconfigure/0 🧚

reconfigure() -> ok | {error, term()}.

reconfigures Logger using the updated kernel configuration that got set after the kernel application was already loaded. 🌈

⚠️ BESTIE. READ THIS ONE. FOR REAL. this is meant to be run only by the build tools β€” not manually while the app is alive. doing it by hand can cause missing log entries and we do not want that energy. 😭

so here's what goes down: before reconfiguring, the simple logger handler gets added to capture log events while the logging infrastructure is still booting, and it prints them to standard output. then once the default handler is added back, every log event the simple handler caught gets replayed to the default handler, and the simple handler is removed. πŸ‘‘ notice though β€” if u don't add the default handler, the simple handler just… persists. it's giving clingy. πŸ™ˆ

πŸ’œ remove_handler/1 πŸ’œ

remove_handler(HandlerId) -> ok | {error, term()}
                          when HandlerId :: logger_handler:id().

removes the handler that matches HandlerId. bye bye πŸ‘‹

πŸŽ€ remove_handler_filter/2 πŸŽ€

remove_handler_filter(HandlerId, FilterId) -> ok | {error, term()}
                                   when
                                       HandlerId :: logger_handler:id(),
                                       FilterId :: filter_id().

removes the filter matching FilterId from the handler matching HandlerId. surgically removing the filter from the handler, we love to see it πŸ’…

⭐ remove_primary_filter/1 ⭐

remove_primary_filter(FilterId) -> ok | {error, term()}
                                   when FilterId :: filter_id().

removes the primary filter matching FilterId from Logger. the primary one, bestie, don't get it twisted 🫢

πŸ¦‹ set_application_level/2 πŸ¦‹

set_application_level(Application, Level) ->
                                   ok | {error, not_loaded}
                                   when
                                       Application :: atom(),
                                       Level :: level() | all | none.

sets the log level for every single module of the application u name. 🌸

this is a convenience function, iykyk β€” under the hood it just calls logger:set_module_level/2 for each module that belongs to that application. one call, all the modules. efficient queen. πŸ‘‘

🌈 set_handler_config/2 🌈

set_handler_config(HandlerId, Config) -> ok | {error, term()}
                                when
                                    HandlerId :: logger_handler:id(),
                                    Config :: logger_handler:config().

sets config data for the handler u name. heads up tho β€” this overwrites the handler's current configuration. it's giving "fresh start", not "gentle edit". πŸ’€

wanna modify what's already there instead? use update_handler_config/2. or, if u need a fancier merge, read the current config with get_handler_config/1, do the merge urself, then write the new config back with this function. ✨

and if a key gets removed compared to the current config: if Logger knows that key, the default value gets used. if it's a custom key, it's up to the handler implementation whether the value is removed or a default value is inserted. so like… custom keys are a vibe check u gotta trust the handler on. πŸ™ˆ

πŸ’… set_handler_config/3 πŸ’…

set_handler_config(HandlerId, level, Level) -> Return
                            when
                                HandlerId :: logger_handler:id(),
                                Level :: level() | all | none,
                                Return :: ok | {error, term()};
                        (HandlerId, filter_default, FilterDefault) ->
                            Return
                            when
                                HandlerId :: logger_handler:id(),
                                FilterDefault :: log | stop,
                                Return :: ok | {error, term()};
                        (HandlerId, filters, Filters) -> Return
                            when
                                HandlerId :: logger_handler:id(),
                                Filters :: [{filter_id(), filter()}],
                                Return :: ok | {error, term()};
                        (HandlerId, formatter, Formatter) -> Return
                            when
                                HandlerId :: logger_handler:id(),
                                Formatter ::
                                    {module(), formatter_config()},
                                Return :: ok | {error, term()};
                        (HandlerId, config, Config) -> Return
                            when
                                HandlerId :: logger_handler:id(),
                                Config :: term(),
                                Return :: ok | {error, term()}.

adds or updates config data for the handler u name. if the Key u pass already exists, its value gets changed to whatever u gave it. if it doesn't exist yet? it gets added. it's giving "i'll make room for u". πŸ₯°

now, if the value u pass is incomplete β€” which can totes happen with the config key β€” it's up to the handler implementation how the unspecified parts get set. for all the handlers in the Kernel application, unspecified data for the config key gets set to default values. and if u only wanna update the specified data and keep the existing config for everything else, use update_handler_config/3. πŸŽ€

want the full tea on the different parameters? go look at the definition of the logger_handler:config/0 type. πŸ“š

πŸ”₯ set_module_level/2 πŸ”₯

set_module_level(Modules, Level) -> ok | {error, term()}
                              when
                                  Modules :: [module()] | module(),
                                  Level :: level() | all | none.

sets the log level for the modules u name. πŸ“£

the log level of a module overrides the primary log level of Logger for log events that come from that module. but β€” and this is the important bit β€” it does not override the level configuration for any handler. two different layers, bestie, don't confuse them. πŸ’…

okay let's do the example, it's so much clearer:

  • say the primary log level for Logger is info, and u got one handler, h1, with level info, and one handler, h2, with level debug.
  • with that config, no debug messages will be logged, because they all get stopped by the primary log level.
  • now if u set the level for mymodule to debug, then debug events from that module will get logged by handler h2 β€” but not by handler h1.
  • debug events from other modules? still not logged. sorry babe. πŸ™ˆ
  • wanna change the primary log level for Logger? that's set_primary_config(level, Level).
  • wanna change the log level for a handler? that's set_handler_config(HandlerId, level, Level).
🚨 NOTE: the originating module for a log event is only detected if the key mfa exists in the metadata, and it's associated with {Module, Function, Arity}. when log macros are used, this association gets added to all log events automatically. ✨ but if an API function gets called directly, without a macro, the logging client has to explicitly add this info if u want module levels to have any effect at all. no mfa, no effect, no cap. πŸ’€

πŸ“ set_primary_config/1 πŸ“

set_primary_config(Config) -> ok | {error, term()}
                            when Config :: primary_config().

sets primary configuration data for Logger. again β€” this overwrites the current configuration. 🫢

wanna modify the existing config instead? use update_primary_config/1. or if u need a more complex merge, read the current config with get_primary_config/0, do the merge, then write the new configuration back with this function. ✨

and if a key gets removed compared to the current config? the default value is used. easy. 🌸

πŸ‘‘ set_primary_config/2 πŸ‘‘

set_primary_config(level, Level) -> ok | {error, term()}
                            when Level :: level() | all | none;
                        (filter_default, FilterDefault) ->
                            ok | {error, term()}
                            when FilterDefault :: log | stop;
                        (filters, Filters) -> ok | {error, term()}
                            when Filters :: [{filter_id(), filter()}];
                        (metadata, Meta) -> ok | {error, term()}
                            when Meta :: metadata().

four flavours, one function, main character energy fr fr. πŸŒˆβœ‹

Adding or updating primary configuration data for Logger, bestie πŸ’–. If the given Key is already there, its value gets swapped for the new one. If it's not there, it gets added. Simple as.

The metadata key was added in OTP 24.0 β€” so if you're on something older, that key is not gonna show up for you, no cap.


🌸 set_process_metadata(Meta) -> ok when Meta :: metadata().

Set metadata that Logger is just gonna automatically insert into all log events produced on the current process. Like, every event from this process shows up wearing this little outfit. Slay.

Location data produced by the log macros, and/or metadata given as an argument to the log call (API function or macro), get merged with the process metadata. And when the same keys occur? Here's the hierarchy, bestie, pay attention:

  • values from the metadata argument to the log call overwrite values from the process metadata
  • the process metadata overwrites values from the location data

So log-call metadata > process metadata > location data. The loudest one wins ✨.

Heads up: subsequent calls to this function overwrite previous data set. Not merge. Overwrite. If you wanna update existing data instead of nuking it, go see update_process_metadata/1 🫢

πŸ¦‹ set_proxy_config(Config) -> ok | {error, term()} when Config :: olp_config().

Set configuration data for the Logger proxy. This overwrites the current proxy configuration completely. Keys you did not specify in the Config map just get default values.

Wanna modify the existing config instead of replacing it? Use update_proxy_config/1. Or, if you need a more complex merge, read the current config with get_proxy_config/0, do your merge, then write it back with this function. DIY merge, we love to see it πŸ’….

For more info about the proxy, go read the section Logger Proxy in the Kernel User's Guide.


🧚 timestamp() -> timestamp().

Returns a timestamp you can insert as the time field in the meta data for a log event. It's produced with os:system_time(microsecond).

Notice: Logger automatically inserts a timestamp in the meta data unless it already exists. So this function is exported for that rare case when you need the timestamp taken at a different point in time than when the log event is actually issued. Rare case girlies, this one's for you ⭐

πŸ’œ unset_application_level(Application) -> ok | {error, {not_loaded, Application}} when Application :: atom().

Unset the log level for all the modules of the specified application.

It's a utility function, lowkey a little assistant: it calls logger:unset_module_level/2 for each module associated with an application. Iconic delegation behavior.


πŸŽ€ unset_module_level() -> ok.

Remove module specific log settings. After this, the primary log level is used for all modules. Everyone back to default, periodt.


🌈 unset_module_level(Modules) -> ok when Modules :: [module()] | module().

Remove module specific log settings. After this, the primary log level is used for the specified modules. Only the ones you named, king.


πŸ“ unset_process_metadata() -> ok.

Delete data set with set_process_metadata/1 or update_process_metadata/1. Gone, bye, we barely knew her πŸ’–


πŸ‘‘ update_formatter_config(HandlerId, FormatterConfig) -> ok | {error, term()}

update_formatter_config(HandlerId, FormatterConfig) ->
                                 ok | {error, term()}
                                 when
                                     HandlerId :: logger_handler:id(),
                                     FormatterConfig ::
                                         formatter_config().

Update the formatter configuration for the specified handler.

The new configuration is merged with the existing formatter configuration. Softly, gently, no overwriting.

If you wanna overwrite the existing configuration without any merge at all, use:

set_handler_config(HandlerId, formatter,
           {FormatterModule, FormatterConfig}).

That's the hard reset. This one's the glow-up-in-place ✨


πŸ’€ update_handler_config(HandlerId, Config) -> ok | {error, term()}

update_handler_config(HandlerId, Config) -> ok | {error, term()}
                               when
                                   HandlerId :: logger_handler:id(),
                                   Config :: logger_handler:config().

Update configuration data for the specified handler. This function behaves as if it was implemented like this:

{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.


πŸ”₯ update_handler_config(HandlerId, level, Level) -> Return

update_handler_config(HandlerId, level, Level) -> Return
                               when
                                   HandlerId :: logger_handler:id(),
                                   Level :: level() | all | none,
                                   Return :: ok | {error, term()};
                           (HandlerId, filter_default, FilterDefault) ->
                               Return
                               when
                                   HandlerId :: logger_handler:id(),
                                   FilterDefault :: log | stop,
                                   Return :: ok | {error, term()};
                           (HandlerId, filters, Filters) -> Return
                               when
                                   HandlerId :: logger_handler:id(),
                                   Filters :: [{filter_id(), filter()}],
                                   Return :: ok | {error, term()};
                           (HandlerId, formatter, Formatter) -> Return
                               when
                                   HandlerId :: logger_handler:id(),
                                   Formatter ::
                                       {module(), formatter_config()},
                                   Return :: ok | {error, term()};
                           (HandlerId, config, Config) -> Return
                               when
                                   HandlerId :: logger_handler:id(),
                                   Config :: term(),
                                   Return :: ok | {error, term()}.

Add or update configuration data for the specified handler. If the given Key already exists, its associated value gets changed to the given value. If it doesn't exist, it gets added. Same energy as always πŸ’…

Now here's the spicy part. If the value is incomplete β€” which, for example, can happen 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 not changed. So if you wanted to reset unspecified data back to default values, use set_handler_config/3 instead. Don't come crying to this function about it πŸ™ˆ

See the definition of the logger_handler:config/0 type for more info about the different parameters.


🌸 update_primary_config(Config) -> ok | {error, term()}

update_primary_config(Config) -> ok | {error, term()}
                               when Config :: primary_config().

Update primary configuration data for Logger. This function behaves as if it was implemented like this:

Old = logger:get_primary_config(),
logger:set_primary_config(maps:merge(Old, Config)).

To overwrite the existing configuration without any merge, use set_primary_config/1.


🫢 update_process_metadata(Meta) -> ok when Meta :: metadata().

Set or update metadata to use when logging from the current process.

If process metadata already exists for the current process, this function behaves as if it was implemented like this:

logger:set_process_metadata(maps:merge(logger:get_process_metadata(), Meta)).

And if no process metadata exists? It just behaves like set_process_metadata/1. Either way you're covered, bestie πŸŽ€


⭐ update_proxy_config(Config) -> ok | {error, term()}

update_proxy_config(Config) -> ok | {error, term()}
                             when Config :: olp_config().

Update configuration data for the Logger proxy. This function behaves as if it was implemented like this:

Old = logger:get_proxy_config(),
logger:set_proxy_config(maps:merge(Old, Config)).

To overwrite the existing configuration without any merge, use set_proxy_config/1.

For more information about the proxy, see the section Logger Proxy in the Kernel User's Guide.


πŸ¦‹ warning(...)

warning(String :: unicode:chardata(), Metadata :: metadata()) ->
                 ok;
             (Report :: report(), Metadata :: metadata()) -> ok;
             (Format :: io:format(), Args :: [term()]) -> ok;
             (Fun :: msg_fun(), FunArgs :: term()) -> ok.

Create a warning log event. ⚠️ Big warning-energy, but make it fashion.

  • Equivalent to log(warning, StringOrReport, Metadata) if you call it as warning(StringOrReport, Metadata).
  • Equivalent to warning(FormatOrFun, Args, #{}) if you call it as warning(FormatOrFun, Args).

So it's the same thing with the metadata already filled in for you when you don't pass any. Convenient king behavior, honestly πŸ’–


That's the whole page, bestie β€” you made it to the end πŸŽ‰ And a lil credit where credit is due: this masterpiece is brought to you by Ericsson AB, from kernel 11.0.3, and it's the logger(3) manual page. Go forth and log responsibly, you gorgeous nerd πŸ‘‘πŸ’…βœ¨

πŸ“¦ where this page comes from