Confused by the new logger configuration

Recently I’ve been struggling to configure the logger in Elixir 1.15.x.

I created my logger handler

defmodule Foo.LoggerHandler do
  @behaviour :gen_event

  @impl true
  def init(args) do
    IO.inspect(args, label: "ARGS IN HANDLER INIT")

    {:ok, {:this_is_the_state, args}}
  end

  @impl true
  def handle_call(request, state) do
    IO.inspect(request, label: "REQUEST IN HANDLER HANDLE CALL")
    IO.inspect(state, label: "STATE IN HANDLER HANDLE CALL")

    {:ok, "blah blah", state}
  end

  @impl true
  def handle_event(event, state) do
    IO.inspect(event, label: "EVENT IN HANDLER HANDLE EVENT")
    IO.inspect(state, label: "STATE IN HANDLER HANDLE EVENT")

    {:ok, state}
  end
end

and a formatter module (I don’t know if this is the correct way):

defmodule Foo.LoggerFormatter do
  def format(event, config) do
    IO.inspect(event, label: "EVENT IN FORMATTER")
    IO.inspect(config, label: "CONFIG IN FORMATTER")

    "This is the result of the formatter"
  end
end

The config.exs is pretty simple:

import Config

config :logger, :default_handler, false

config :foo, :logger, [
  {
    :handler,
    :my_handler,
    Foo.LoggerHandler,
    %{
      config: %{
        xxx: 123,
        yyy: 456
      },
      formatter: Foo.LoggerFormatter
    }
  }
]

And I added this line to my application.ex:

defmodule Foo.Application do
  use Application

  @impl true
  def start(_type, _args) do
    LoggerBackends.add(Foo.LoggerHandler)  # <-----  Just this line

    children = []

    opts = [strategy: :one_for_one, name: Foo.Supervisor]
    Supervisor.start_link(children, opts)
  end
end

When I ran iex -S mix, I saw the following messages printed to the terminal:

ARGS IN HANDLER INIT: Foo.LoggerHandler

It seems that my logger handler does not get the configuration.

When I ran Logger.info aaa: 111, bbb: 222 in iex, I saw

EVENT IN HANDLER HANDLE EVENT: {:info, #PID<0.183.0>,
 {Logger, "[aaa: 111, bbb: 222]", {{2023, 11, 22}, {16, 19, 54, 873}},
  [
    erl_level: :info,
    pid: #PID<0.192.0>,
    time: 1700641194873059,
    gl: #PID<0.183.0>,
    domain: [:elixir]
  ]}}
STATE IN HANDLER HANDLE EVENT: {:this_is_the_state, Foo.LoggerHandler}

The formatter is definitely not called at all.

Where did I do wrong? Thanks in advance.

3 Likes