Logger log strings evaluation

Ciao,

My app produces a high amount of info and debug logs, so in production the level is configured to “warning”. Are the contents of lower levels logs (info and debug) evaluated?

In other words, is the following log string evaluated even though it is not written to output?

Logger.info("Hello #{world}")

Thanks in advance

No, Logger macros are used for 2 things:

  • Dynamically evaluate the message only when needed.
  • Allow compile-time purging

In your case this will not be evaluated when the current level is higher than :info. It can be easily tested by:

defmodule Foo do
  require Logger

  def log_msg do
    Process.sleep(2000)
    "Foo"
  end

  def log, do: Logger.info(log_msg())
end

Logger.configure(level: :all)
Foo.log()

Logger.configure(level: :none)
Foo.log()
2 Likes

It depends.

If you purge lower log levels during compilation, of course no evaluation will take place.

If though you the level doesn’t get purged, then "Hello, #{world}“ gets evaluated and then filtered.

You can as well wrap it in a function, which will get evaluated only if necessary.

Also newer versions of logger sometimes are able to recognize dynamic string building and wrap it a fn during compile time unless purged.

This is no longer true. Now both these ways are mostly equivalent and passing function as a first argument is no longer needed for lazy evaluation of the message.

1 Like