View Source logger (kernel v10.0.1)

API module for Logger, the standard logging facility in Erlang/OTP.

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:

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

Summary

Types

Configuration used when adding or updating a handler.

A filter which can be installed as a handler filter, or as a primary filter in Logger.

The second argument to the filter fun.

A unique identifier for a filter.

The return value from the filter fun.

Configuration data for the formatter. See logger_formatter for an example of a formatter implementation.

Handler configuration data for Logger.

A unique identifier for a handler instance.

The severity level for the message to be logged.

A log event passed to filters and handlers

Metadata for the log event.

Overload protection configuration.

Primary configuration data for Logger. The following default values apply

A log report.

A fun which converts a report() to a format string and arguments, or directly to a string.

A timestamp produced with logger:timestamp().

Logging API functions

Create a alert log event.

Create a critical log event.

Create a debug log event.

Create a emergency log event.

Create a error log event.

Create a info log event.

Create a log event at the given log level, with the given message to be logged and metadata.

Create a log event at the given log level, with the given message to be logged and metadata.

Create a notice log event.

Create a warning log event.

Configuration API functions

Add a handler with the given configuration.

Add a filter to the specified handler.

Reads the application configuration parameter logger and calls add_handlers/1 with its contents.

Add a primary filter to Logger.

Look up all current Logger configuration, including primary, handler, and proxy configuration, and module level settings.

Look up the current configuration for all handlers.

Look up the current configuration for the given handler.

Look up the identities for all installed handlers.

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.

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.

Look up the current primary configuration for Logger.

Look up the current configuration for the Logger proxy.

i()

Pretty print all Logger configuration.

Pretty print the Logger configuration.

Remove the handler identified by HandlerId.

Remove the filter identified by FilterId from the handler identified by HandlerId.

Remove the primary filter identified by FilterId from Logger.

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

Set configuration data for the specified handler. This overwrites the current handler configuration.

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.

Set the log level for the specified modules.

Set primary configuration data for Logger. This overwrites the current configuration.

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.

Set metadata which Logger shall automatically insert in all log events produced on the current process.

Set configuration data for the Logger proxy. This overwrites the current proxy configuration. Keys that are not specified in the Config map gets default values.

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

Remove module specific log settings. After this, the primary log level is used for all modules.

Remove module specific log settings. After this, the primary log level is used for the specified modules.

Update the formatter configuration for the specified handler.

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

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.

Update primary configuration data for Logger. This function behaves as if it was implemented as follows

Set or update metadata to use when logging from current process

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

Miscellaneous API functions

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.

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.

Reconfigure Logger using updated kernel configuration that was set after kernel application was loaded.

Return 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).

Types

Link to this type

config_handler()

View Source (since OTP 21.0)
-type config_handler() :: {handler, logger_handler:id(), module(), logger_handler:config()}.

Configuration used when adding or updating a handler.

Link to this type

filter()

View Source (since OTP 21.0)
-type 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.

Link to this type

filter_arg()

View Source (since OTP 21.0)
-type filter_arg() :: term().

The second argument to the filter fun.

Link to this type

filter_id()

View Source (since OTP 21.0)
-type filter_id() :: atom().

A unique identifier for a filter.

Link to this type

filter_return()

View Source (since OTP 21.0)
-type filter_return() :: stop | ignore | log_event().

The return value from the filter fun.

Link to this type

formatter_config()

View Source (since OTP 21.0)
-type formatter_config() :: #{atom() => term()}.

Configuration data for the formatter. See logger_formatter for an example of a formatter implementation.

Link to this type

handler_config()

View Source (since OTP 21.0)
-type handler_config() :: logger_handler:config().

Handler configuration data for Logger.

Note

DEPRECATED: Use logger_handler:config/0 instead.

Link to this type

handler_id()

View Source (since OTP 21.0)
-type handler_id() :: logger_handler:id().

A unique identifier for a handler instance.

Note

DEPRECATED: Use logger_handler:id/0 instead.

Link to this type

level()

View Source (since OTP 21.0)
-type level() :: emergency | alert | critical | error | warning | notice | info | debug.

The severity level for the message to be logged.

Link to this type

log_event()

View Source (since OTP 21.0)
-type log_event() ::
          #{level := level(),
            msg := {io:format(), [term()]} | {report, report()} | {string, unicode:chardata()},
            meta := metadata()}.

A log event passed to filters and handlers

Link to this type

metadata()

View Source (since OTP 21.0)
-type 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:

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.

Link to this type

msg_fun()

View Source (since OTP 21.0)
-type msg_fun() :: fun((term()) -> msg_fun_return() | {msg_fun_return(), metadata()}).
Link to this type

msg_fun_return()

View Source (not exported) (since OTP 21.0)
-type msg_fun_return() :: {io:format(), [term()]} | report() | unicode:chardata() | ignore.
Link to this type

olp_config()

View Source (since OTP 21.0)
-type olp_config() :: logger_handler:olp_config().

Overload protection configuration.

Note

DEPRECATED: Use logger_handler:olp_config/0 instead.

Link to this type

primary_config()

View Source (since OTP 21.0)
-type 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 => []
Link to this type

report()

View Source (since OTP 21.0)
-type report() :: map() | [{atom(), term()}].

A log report.

Link to this type

report_cb()

View Source (since OTP 21.0)
-type 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.

Link to this type

report_cb_config()

View Source (since OTP 21.0)
-type report_cb_config() ::
          #{depth := pos_integer() | unlimited,
            chars_limit := pos_integer() | unlimited,
            single_line := boolean()}.
Link to this type

timestamp()

View Source (since OTP 21.0)
-type timestamp() :: integer().

A timestamp produced with logger:timestamp().

Logging API functions

Link to this function

alert(StringOrReport)

View Source (since OTP 21.0)
-spec alert(String :: unicode:chardata()) -> ok;
           (Report :: report()) -> ok.

Equivalent to emergency(StringOrReport, #{}).

Link to this function

alert(FormatOrFun, Args)

View Source (since OTP 21.0)
-spec 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).

Link to this function

alert(FormatOrFun, Args, Metadata)

View Source (since OTP 21.0)
-spec alert(Format :: io:format(), Args :: [term()], Metadata :: metadata()) -> ok;
           (Fun :: msg_fun(), FunArgs :: term(), Metadata :: metadata()) -> ok.

Equivalent to log(alert, FormatOrFun, Args, Metadata).

Link to this function

critical(StringOrReport)

View Source (since OTP 21.0)
-spec critical(String :: unicode:chardata()) -> ok;
              (Report :: report()) -> ok.

Equivalent to emergency(StringOrReport, #{}).

Link to this function

critical(FormatOrFun, Args)

View Source (since OTP 21.0)
-spec 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).

Link to this function

critical(FormatOrFun, Args, Metadata)

View Source (since OTP 21.0)
-spec critical(Format :: io:format(), Args :: [term()], Metadata :: metadata()) -> ok;
              (Fun :: msg_fun(), FunArgs :: term(), Metadata :: metadata()) -> ok.

Equivalent to log(critical, FormatOrFun, Args, Metadata).

Link to this function

debug(StringOrReport)

View Source (since OTP 21.0)
-spec debug(String :: unicode:chardata()) -> ok;
           (Report :: report()) -> ok.

Equivalent to emergency(StringOrReport, #{}).

Link to this function

debug(FormatOrFun, Args)

View Source (since OTP 21.0)
-spec 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).

Link to this function

debug(FormatOrFun, Args, Metadata)

View Source (since OTP 21.0)
-spec debug(Format :: io:format(), Args :: [term()], Metadata :: metadata()) -> ok;
           (Fun :: msg_fun(), FunArgs :: term(), Metadata :: metadata()) -> ok.

Equivalent to log(debug, FormatOrFun, Args, Metadata).

Link to this function

emergency(StringOrReport)

View Source (since OTP 21.0)
-spec emergency(String :: unicode:chardata()) -> ok;
               (Report :: report()) -> ok.

Equivalent to emergency(StringOrReport, #{}).

Link to this function

emergency(FormatOrFun, Args)

View Source (since OTP 21.0)
-spec 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.

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

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

Link to this function

emergency(FormatOrFun, Args, Metadata)

View Source (since OTP 21.0)
-spec emergency(Format :: io:format(), Args :: [term()], Metadata :: metadata()) -> ok;
               (Fun :: msg_fun(), FunArgs :: term(), Metadata :: metadata()) -> ok.

Equivalent to log(emergency, FormatOrFun, Args, Metadata).

Link to this function

error(StringOrReport)

View Source (since OTP 21.0)
-spec error(String :: unicode:chardata()) -> ok;
           (Report :: report()) -> ok.

Equivalent to emergency(StringOrReport, #{}).

Link to this function

error(FormatOrFun, Args)

View Source (since OTP 21.0)
-spec 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).

Link to this function

error(FormatOrFun, Args, Metadata)

View Source (since OTP 21.0)
-spec error(Format :: io:format(), Args :: [term()], Metadata :: metadata()) -> ok;
           (Fun :: msg_fun(), FunArgs :: term(), Metadata :: metadata()) -> ok.

Equivalent to log(error, FormatOrFun, Args, Metadata).

Link to this function

info(StringOrReport)

View Source (since OTP 21.0)
-spec info(String :: unicode:chardata()) -> ok;
          (Report :: report()) -> ok.

Equivalent to emergency(StringOrReport, #{}).

Link to this function

info(FormatOrFun, Args)

View Source (since OTP 21.0)
-spec 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).

Link to this function

info(FormatOrFun, Args, Metadata)

View Source (since OTP 21.0)
-spec info(Format :: io:format(), Args :: [term()], Metadata :: metadata()) -> ok;
          (Fun :: msg_fun(), FunArgs :: term(), Metadata :: metadata()) -> ok.

Equivalent to log(info, FormatOrFun, Args, Metadata).

Link to this function

log(Level, StringOrReport)

View Source (since OTP 21.0)
-spec log(Level :: level(), String :: unicode:chardata()) -> ok;
         (Level :: level(), Report :: report()) -> ok.

Equivalent to log(Level, StringOrReport, #{}).

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

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 }).

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

Link to this function

log(Level, FunOrFormat, Args, Metadata)

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

Create a log event at the given log level, with the given message to be logged and metadata.

The message and metadata can either be given directly in the arguments, or returned from a fun. Passing a fun instead of the message/metadata directly is useful in scenarios when the message/metadata is very expensive to compute. This is because the fun is only evaluated when the message/metadata is actually needed, which may be not at all if the log event is not to be logged. Examples:

%% 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 }).

When metadata is given both as an argument and returned from the fun they are merged. If equal keys exists the values are taken from the metadata returned by the fun.

Link to this function

notice(StringOrReport)

View Source (since OTP 21.0)
-spec notice(String :: unicode:chardata()) -> ok;
            (Report :: report()) -> ok.

Equivalent to emergency(StringOrReport, #{}).

Link to this function

notice(FormatOrFun, Args)

View Source (since OTP 21.0)
-spec notice(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 notice log event.

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

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

Link to this function

notice(FormatOrFun, Args, Metadata)

View Source (since OTP 21.0)
-spec notice(Format :: io:format(), Args :: [term()], Metadata :: metadata()) -> ok;
            (Fun :: msg_fun(), FunArgs :: term(), Metadata :: metadata()) -> ok.

Equivalent to log(notice, FormatOrFun, Args, Metadata).

Link to this function

warning(StringOrReport)

View Source (since OTP 21.0)
-spec warning(String :: unicode:chardata()) -> ok;
             (Report :: report()) -> ok.

Equivalent to emergency(StringOrReport, #{}).

Link to this function

warning(FormatOrFun, Args)

View Source (since OTP 21.0)
-spec 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.

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

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

Link to this function

warning(FormatOrFun, Args, Metadata)

View Source (since OTP 21.0)
-spec warning(Format :: io:format(), Args :: [term()], Metadata :: metadata()) -> ok;
             (Fun :: msg_fun(), FunArgs :: term(), Metadata :: metadata()) -> ok.

Equivalent to log(warning, FormatOrFun, Args, Metadata).

Configuration API functions

Link to this function

add_handler(HandlerId, Module, Config)

View Source (since OTP 21.0)
-spec 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.

Link to this function

add_handler_filter(HandlerId, FilterId, Filter)

View Source (since OTP 21.0)
-spec 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.

Link to this function

add_handlers/1

View Source (since OTP 21.0)
-spec add_handlers(Application) -> ok | {error, term()} when Application :: atom();
                  (HandlerConfig) -> ok | {error, term()} when HandlerConfig :: [config_handler()].

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, #{}}]}]}].
Link to this function

add_primary_filter(FilterId, Filter)

View Source (since OTP 21.0)
-spec add_primary_filter(FilterId, Filter) -> ok | {error, term()}
                            when FilterId :: filter_id(), Filter :: filter().

Add a primary filter to Logger.

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

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

Link to this function

get_config()

View Source (since OTP 21.0)
-spec 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.

Link to this function

get_handler_config()

View Source (since OTP 21.0)
-spec get_handler_config() -> [Config] when Config :: logger_handler:config().

Look up the current configuration for all handlers.

Link to this function

get_handler_config(HandlerId)

View Source (since OTP 21.0)
-spec 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.

Link to this function

get_handler_ids()

View Source (since OTP 21.0)
-spec get_handler_ids() -> [HandlerId] when HandlerId :: logger_handler:id().

Look up the identities for all installed handlers.

Link to this function

get_module_level()

View Source (since OTP 21.0)
-spec 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.

Link to this function

get_module_level(Modules)

View Source (since OTP 21.0)
-spec 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.

Link to this function

get_primary_config()

View Source (since OTP 21.0)
-spec get_primary_config() -> Config when Config :: primary_config().

Look up the current primary configuration for Logger.

Link to this function

get_process_metadata()

View Source (since OTP 21.0)
-spec get_process_metadata() -> Meta | undefined when Meta :: metadata().

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

Link to this function

get_proxy_config()

View Source (since OTP 21.3)
-spec 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.

-spec i() -> ok.

Pretty print all Logger configuration.

Link to this function

i(What)

View Source (since OTP 21.3)
-spec i(What) -> ok when What :: primary | handlers | proxy | modules | logger_handler:id().

Pretty print the Logger configuration.

Link to this function

remove_handler(HandlerId)

View Source (since OTP 21.0)
-spec remove_handler(HandlerId) -> ok | {error, term()} when HandlerId :: logger_handler:id().

Remove the handler identified by HandlerId.

Link to this function

remove_handler_filter(HandlerId, FilterId)

View Source (since OTP 21.0)
-spec remove_handler_filter(HandlerId, FilterId) -> ok | {error, term()}
                               when HandlerId :: logger_handler:id(), FilterId :: filter_id().

Remove the filter identified by FilterId from the handler identified by HandlerId.

Link to this function

remove_primary_filter(FilterId)

View Source (since OTP 21.0)
-spec remove_primary_filter(FilterId) -> ok | {error, term()} when FilterId :: filter_id().

Remove the primary filter identified by FilterId from Logger.

Link to this function

set_application_level(Application, Level)

View Source (since OTP 21.1)
-spec set_application_level(Application, Level) -> ok | {error, not_loaded}
                               when Application :: atom(), Level :: level() | all | none.

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

This function is a convenience function that calls logger:set_module_level/2 for each module associated with an application.

Link to this function

set_handler_config(HandlerId, Config)

View Source (since OTP 21.0)
-spec set_handler_config(HandlerId, Config) -> ok | {error, term()}
                            when HandlerId :: logger_handler:id(), Config :: logger_handler:config().

Set configuration data for the specified handler. This overwrites the current handler configuration.

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.

Link to this function

set_handler_config(HandlerId, Key, Value)

View Source (since OTP 21.0)
-spec 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()}.

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.

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 logger_handler:config/0 type for more information about the different parameters.

Link to this function

set_module_level(Modules, Level)

View Source (since OTP 21.0)
-spec set_module_level(Modules, Level) -> ok | {error, term()}
                          when Modules :: [module()] | module(), Level :: level() | all | none.

Set the log level for the specified modules.

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.

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.

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 key mfa exists 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.

Link to this function

set_primary_config(Config)

View Source (since OTP 21.0)
-spec set_primary_config(Config) -> ok | {error, term()} when Config :: primary_config().

Set primary configuration data for Logger. This overwrites the current configuration.

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.

Link to this function

set_primary_config(Key, Value)

View Source (since OTP 21.0)
-spec 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().

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.

The metadata key was added in OTP 24.0.

Link to this function

set_process_metadata(Meta)

View Source (since OTP 21.0)
-spec set_process_metadata(Meta) -> ok when Meta :: metadata().

Set metadata which Logger shall automatically insert in all log events produced on the current process.

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.

Link to this function

set_proxy_config(Config)

View Source (since OTP 21.3)
-spec set_proxy_config(Config) -> ok | {error, term()} when 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 gets 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.

Link to this function

unset_application_level(Application)

View Source (since OTP 21.1)
-spec unset_application_level(Application) -> ok | {error, {not_loaded, Application}}
                                 when 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.

Link to this function

unset_module_level()

View Source (since OTP 21.0)
-spec unset_module_level() -> ok.

Remove module specific log settings. After this, the primary log level is used for all modules.

Link to this function

unset_module_level(Modules)

View Source (since OTP 21.0)
-spec 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.

Link to this function

unset_process_metadata()

View Source (since OTP 21.0)
-spec unset_process_metadata() -> ok.

Delete data set with set_process_metadata/1 or update_process_metadata/1.

Link to this function

update_formatter_config(HandlerId, FormatterConfig)

View Source (since OTP 21.0)
-spec 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.

To overwrite the existing configuration without any merge, use

set_handler_config(HandlerId, formatter,
	      {FormatterModule, FormatterConfig}).
Link to this function

update_formatter_config(HandlerId, Key, Value)

View Source (since OTP 21.0)
-spec update_formatter_config(HandlerId, Key, Value) -> ok | {error, term()}
                                 when HandlerId :: logger_handler:id(), Key :: atom(), Value :: term().

Equivalent to update_formatter_config(HandlerId, #{Key => Value}).

Link to this function

update_handler_config(HandlerId, Config)

View Source (since OTP 21.0)
-spec 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 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 .

Link to this function

update_handler_config(HandlerId, Key, Value)

View Source (since OTP 21.2)
-spec 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 will be changed to the given value. If it does not exist, it will be added.

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 not changed. To reset unspecified data to default values, use set_handler_config/3.

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

Link to this function

update_primary_config(Config)

View Source (since OTP 21.0)
-spec 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 as follows:

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 .

Link to this function

update_process_metadata(Meta)

View Source (since OTP 21.0)
-spec update_process_metadata(Meta) -> ok when Meta :: metadata().

Set or update metadata to use when logging from current process

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

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

If no process metadata exists, the function behaves as set_process_metadata/1 .

Link to this function

update_proxy_config(Config)

View Source (since OTP 21.3)
-spec 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 as follows:

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 section Logger Proxy in the Kernel User's Guide.

Miscellaneous API functions

Link to this function

compare_levels(Level1, Level2)

View Source (since OTP 21.0)
-spec 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.

Link to this function

format_report(Report)

View Source (since OTP 21.0)
-spec 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.

Link to this function

reconfigure()

View Source (since OTP 24.2)
-spec reconfigure() -> ok | {error, term()}.

Reconfigure Logger using updated kernel configuration that was set after kernel application was loaded.

Beware, that this is meant to be run only by the build tools, not manually during application lifetime, as this may cause missing log entries.

Link to this function

timestamp()

View Source (since OTP 21.3)
-spec timestamp() -> timestamp().

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