sezaru

sezaru

How to add custom metadata for errors in process

Sometimes I get some errors in my log that doesn’t have enough information to allow me to reproduce the issue.

So I was wondering how can I add custom metadata to a process so when a new error is logged, that metadata is show too.

I know that you can do something like this with Logger.metadata, but AFAIK, this only works with structured data, basically you define in the config the keys you accept as metadata and that is what I you can use in all your project.

What I want is to be able to add custom data depending on what I’m doing. For example, if I’m processing some data from a crypto market like BTC_USDT, then I would like my log to show something like market: BTC_USDT when an error is logged.

In other words, I don’t want to have to fill the metadata config with a bunch of keys for every time I want to add a new metadata in my codebase.

config :logger, :console,
 metadata: [...]

Marked As Solved

sezaru

sezaru

I think I figured it out.

What I did was add a :other field to my metadata array, then i adde a case for my custom log formatter to handle that field.

So my config became like this:

config :logger, :console,
  level: :debug,
  metadata: [:other],
  format: {Log.Formatter, :format}

And my formatter like this:

defmodule Log.Formatter do
  @moduledoc false

  alias IO.ANSI

  @color_reset ANSI.reset()
  @highlight ANSI.light_magenta()

  def format(:debug, message, timestamp, metadata),
    do: format(:debug, message, timestamp, metadata, ANSI.cyan())

  def format(:info, message, timestamp, metadata),
    do: format(:info, message, timestamp, metadata, ANSI.green())

  def format(:notice, message, timestamp, metadata),
    do: format(:notice, message, timestamp, metadata, ANSI.light_yellow())

  def format(:warn, message, timestamp, metadata),
    do: format(:warn, message, timestamp, metadata, ANSI.yellow())

  def format(:warning, message, timestamp, metadata),
    do: format(:warn, message, timestamp, metadata, ANSI.yellow())

  def format(:error, message, timestamp, metadata),
    do: format(:error, message, timestamp, metadata, ANSI.red())

  def format(:critical, message, timestamp, metadata),
    do: format(:critical, message, timestamp, metadata, ANSI.yellow_background())

  def format(:alert, message, timestamp, metadata),
    do: format(:alert, message, timestamp, metadata, ANSI.light_red_background())

  def format(:emergency, message, timestamp, metadata),
    do: format(:emergency, message, timestamp, metadata, ANSI.red_background())

  defp format(level, message, timestamp, metadata, color) do
    date_time = format_date_time(timestamp)
    metadata = format_metadata(metadata, color)

    "\n#{color}#{date_time} [#{level}] #{metadata}\n↳ #{message}#{@color_reset}\n"
  rescue
    _ -> "Could not format message: #{inspect({level, message, timestamp, metadata})}"
  end

  # This is the function I added
  defp format_metadata([{:other, value} | rest], color) do
    "#{@highlight}#{inspect(value)}#{color} " <> format_metadata(rest, color)
  end

  defp format_metadata([{_key, value} | rest], color) do
    "#{inspect(value)} " <> format_metadata(rest, color)
  end

  defp format_metadata([], _), do: ""

  defp format_date_time({date, time}) do
    alias Logger.Formatter

    "#{Formatter.format_date(date)} #{Formatter.format_time(time)}"
  end
end

That way, I can send any data to it using the other metadata,

For example, Logger.error("blibs", other: %{blibs: 2}) will be logged as:

2025-07-14 19:23:44.530 [error] #PID<0.770.0> %{blibs: 2} 
↳ blibs

Also Liked

axelson

axelson

Scenic Core Team

You can also set metadata: :all to log whatever metadata you pass.

Where Next?

Popular in Questions Top

Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
Kagamiiiii
Student &amp; New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New

We're in Beta

About us Mission Statement