简体   繁体   中英

Elixir Logger customize metadata format

In config.exs, I have config :logger, :console, metadata: [:module, :function, :line]

This will add module=Module function=my_func/1 line=41 to the beginning of every debug message.

Instead, I would like to format the message in a more easily readable way for me: Module.my_func/1(41) .

Is it possible to segment out specific metadata in the config format specifier? It seems to me that I should be able to do something like format: "$metadata[module].$metadata[function]($metadata[line])" but this is not possible.

Yes, this is possible, but I think you have to use the :mfa metadata option .

In your config:

config :logger, :console,
  level: :debug,
  metadata: [:mfa, :line],
  format: {MyLogFormatter, :format}

Then in your custom MyLogFormatter module, you would implement something like this:

def format(level, message, timestamp, metadata) do
    src =
      case Keyword.get(metadata, :mfa) do
        {m, f, a} -> "module=#{m} function=#{f}/#{a} line=#{Keyword.get(metadata, :line)}"
        _ -> nil
      end
    
    string = "#{src} #{message}"
    string <> "\n"
  end

You could add a clause or two if you wanted custom behavior depending on the level, but be careful when customizing this because it can really knee-cap your app if there's a problem.

If it works for you to adjust the log format using the formatting string, that is less work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM