Skip to content

Logger.Formatter.format/2 #13962

@David-Klemenc

Description

@David-Klemenc

Elixir and Erlang/OTP versions

Erlang/OTP 27 [erts-15.1.2] [source] [64-bit] [smp:16:16] [ds:16:16:10] [async-threads:1] [dtrace]

Elixir 1.17.3 (compiled with Erlang/OTP 27)

Operating system

all

Current behavior

the function Logger.Formatter.format/2 has docs set to false -> @doc false

it is difficult to figure out what the correct setup is to properly use Logger.Formatter.new/1 and the proper setup.

Expected behavior

A config and implementation example would be welcome, something like:
example config.exs

import Config

config :example, :logger, [
  {:handler, :example_log, ExampleLoggerHandler,
   %{
     formatter:
       Logger.Formatter.new(
         format: "$time $metadata[$level] $message",
         # in case you want to save the msg to DB or send it via HTTP
         # the terminal color codes are not necessary
         colors: [enabled: false]
       )
   }}
]

example of logger_handler minimal implementation module:

defmodule ExampleLoggerHandler do
  @behaviour :logger_handler

  @spec log(:logger.log_event(), :logger_handler.config()) :: term()
  def log(event, config) do
    {formatter, formatterConfig} =
      Map.get(config, :formatter)

    message =
      apply(formatter, :format, [event, formatterConfig])
      |> IO.chardata_to_string()

    # you have a nicely formatted message now
    # you can save the message and meta-data into a DB, send it somewhere via HTTP
    # or do whatever you want
  end
end

Here I used apply/3 to make it more clear what is going on. Basically the Logger.Formatter.new/1 should hint at the existence of Logger.Formatter.format/2 and how it is supposed to be called.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions