elixir-tesla / tesla

The flexible HTTP client library for Elixir, with support for middleware and multiple adapters.
MIT License
2.01k stars 349 forks source link

Add metadata to logger #631

Open teamon opened 1 year ago

teamon commented 1 year ago

wip, testing in progress

teamon commented 1 year ago

@yordis wdyt of this as an idea?

yordis commented 3 months ago

Recently, I had to send the data somehow, I ended up doing the following:

defmodule Umbrella.Tesla.Logger do
  def log_level(%Tesla.Env{status: status}) when status in 400..499, do: :warning
  def log_level(_env), do: :default

  def log_formatter(req, {:error, reason}, time) do
    %{
      time: time,
      method: upper_case_method(req),
      url: req.url,
      path: req.opts[:req_url],
      req_body: log_env_body(req),
      reason: inspect(reason)
    }
  end

  def log_formatter(req, {:ok, resp}, time) do
    %{
      time: time,
      status: resp.status,
      method: upper_case_method(req),
      url: req.url,
      path: req.opts[:req_url],
      req_body: log_env_body(req),
      resp_body: log_env_body(resp)
    }
  end

  defp log_env_body(%Tesla.Env{status: status} = env) when status >= 400 do
    inspect(env.body)
  end

  defp log_env_body(_), do: "[REDACTED]"

  defp upper_case_method(%Tesla.Env{} = env) do
    env.method
    |> to_string()
    |> String.upcase()
  end
end

As long as the metadata is under a given key tesla: [....] I do not see any issue, although, I still believe that structured logging is much better.

Being said, the ultimate way to deal with this is to simple allow the user to do Logger calls themselves and give them enough information to know what to do with it.

I think it was a misdirection to call Logger ourselves. Except for the debug flag!