Logger: custom log formatter

When defining a custom formatter for the Elixir Logger, is there a way for a structured report to be passed to it as a map or a Keyword list instead of being formatted as the iolist?

I.e. for a call Logger.info(%{test: "report"}), I’d like it to be accessible in the formatter in the structured form:

config.ex:

config: :logger, :console,
  format: {MyFormatter, :format}

formatter.ex:

defmodule MyFormatter do
  def format(level, msg, {date, time}, meta) do
     %% The `msg` here is an iolist instead of being passed as a map or Keyword.t
  end
end

Structured data is only available to erlang :logger handlers, not elixir Logger backends.

There’s an entire thread worth of information in there on structured logging. I’ve since updated the module to handle 404’s and exceptions a bit better and been using it in production for a long time now. If interested, I can publish the updated solution somewhere.

1 Like