Adding node name/id to log metadata

Is it possible to add a node name/id to logger output?

I’m not thinking of a great way to set it for every process in your app, which I’m assuming is your question? For a single process you can do something like Logger.metadata(node: Node.self()). For a single log you could do Logger.info("my log message", node: Node.self()). You would need to configure logger to include :node in the metadata it prints.

One option if you’re looking to add it for every log message would be to create your own formatter that passes everything along to the default formatter with one exception: it adds the node to the metadata.

defmodule MyApp.LogFormatter do
  @pattern Logger.Formatter.compile("\n$time $metadata[$level] $levelpad$message\n")

  def format(level, message, timestamp, metadata) do
    Logger.Formatter.format(@pattern, level, message, timestamp, [{:node, Node.self()} | metadata])
  end
end

You’ll need to swap out the formatter in your config:

config :logger, :console,
  format: {MyApp.LogFormatter, :format},
  metadata: [:node, ...]
1 Like