Logger ignores configuration when logging at compile-time

All the code allowing to reproduce my issue can be found here:

To illustrate my issue, I wrote the following simple macro:

defmodule Math do
  defmacro square_of(number) do
    require Logger

    Logger.debug("Received AST: #{inspect(number)}")
    number = Macro.expand(number, __CALLER__)
    Logger.debug("Expanded AST: #{inspect(number)}")

    quote bind_quoted: [number: number] do
      require Logger

      square = number * number
      Logger.info("Square of #{number} is #{square}.")
      square
    end
  end
end

When I use the above Math.square_of/1 macro, the 2 Logger.debug calls ignore the Logger configuration in config/config.exs and are instead formatted using the Logger’s default format!!

Here is a simple module using the Math.square_of/1 macro:

defmodule MathTest do
  require Math

  def run do
    Math.square_of(3)
    number = 31
    Math.square_of(rem(number, 11) |> div(4))
    :ok
  end
end

When the above MathTest module compiles, 4 debug messages are logged as expected but their format is $time $metadata[$level] $message\n instead of the configured $date $time <<$level>> $levelpad$message\n.

How can I force the Logger to comply with config/config.exs at compile-time?

Thank you in advance!

Have you tried configure or configure_backend?

https://hexdocs.pm/logger/1.12/Logger.html#configure/1

Hello cmo,

Yesssssss!! configure_backend did the trick!!
I added 2 lines to my source code to solve the issue.
The 1st line is defining module attribute @console:
@console Application.get_env(:logger, :console)
And the 2nd was calling configure_backend:
Logger.configure_backend(:console, @console)

So the whole module shown here (with the above 2 lines added) now works just fine:

defmodule Math do
  @console Application.get_env(:logger, :console)

  defmacro square_of(number) do
    require Logger

    Logger.configure_backend(:console, @console)
    Logger.debug("Received AST: #{inspect(number)}")
    number = Macro.expand(number, __CALLER__)
    Logger.debug("Expanded AST: #{inspect(number)}")

    quote bind_quoted: [number: number] do
      require Logger

      square = number * number
      Logger.info("Square of #{number} is #{square}.")
      square
    end
  end
end

Many, many thanks cmo!!

2 Likes