How to get client iP address in elixir logger

Using elixir, I am trying to get client ip address in logger, but not able to get that. Any kind of help will be appreciated.

Hello and welcome to the forum, It is not mentionned if You use Phoenix, but if yes, then You can get remote_ip from conn.

See https://hexdocs.pm/plug/Plug.Conn.html

Thanks for your help. I’m using Phoenix. I’ll try your suggestion.

I added remote IP address to logs of a Phoenix app. Sharing a code snippet here for my future self and the rest of the community:

# lib/my_app_web/endpoint.ex
defmodule MyAppWeb.Endpoint do
  use Phoenix.Endpoint, otp_app: :my_app

  # ...
  plug Plug.RequestId
  plug :logger_metadata_remote_ip
  # ...

  defp logger_metadata_remote_ip(conn, _) do
    Logger.metadata(remote_ip: List.to_string(:inet.ntoa(conn.remote_ip)))
    conn
  end
end

# config/config.exs
config :logger, :default_formatter,
  format: "$time $metadata[$level] $message\n",
  metadata: [:request_id, :remote_ip]

Note that IP addresses are generally treated as personal data under GDPR (and similar regimes), so treat them with appropriate care and consider anonymization.

You likely want to also use remote_ip | Hex as most apps are deployed behind reverse proxy of some kind

Good call. That will vary case by case, though.

There’s also Plug.RewriteOn and the :force_ssl Endpoint config in Phoenix (that uses Plug.SSL under the hood and also rewrites conn fields), so one may also get around without yet another dependency.