OpenTelemetry
Elixir / Erlang
Quick Start

Elixir / Erlang (OpenTelemetry)

Let a coding agent do this setup
1Install the Traceway skills
2Run it in Claude Code

It adds OpenTelemetry to your Elixir service and checks that data arrives. How the setup skill works

Instrument an Elixir service with the OpenTelemetry Erlang and Elixir SDK and export traces, logs and metrics to Traceway over OTLP/HTTP.

The example is a Plug router on Bandit. Phoenix uses the same packages plus opentelemetry_phoenix. See Phoenix. An Erlang application uses the same SDK and the same environment variables, with the otel_tracer macros in place of the Elixir ones.

Traces are stable in this SDK. Metrics and logs come from the opentelemetry_experimental packages, which the OpenTelemetry project marks as in development. They work with Traceway today, and each needs a few lines of setup that traces do not.

Requirements

  • Elixir 1.17 or newer. This guide was checked with Elixir 1.20 on Erlang/OTP 28.
  • A Traceway project created with framework OpenTelemetry, and that project's token.

Install

Add the dependencies and the release settings to mix.exs:

mix.exs
defmodule Demo.MixProject do
  use Mix.Project
 
  def project do
    [
      app: :demo,
      version: "1.0.0",
      elixir: "~> 1.17",
      start_permanent: Mix.env() == :prod,
      deps: deps(),
      releases: [
        demo: [
          applications: [opentelemetry_exporter: :permanent, opentelemetry: :temporary]
        ]
      ]
    ]
  end
 
  def application do
    [
      extra_applications: [:logger],
      mod: {Demo.Application, []}
    ]
  end
 
  defp deps do
    [
      {:bandit, "~> 1.15"},
      {:plug, "~> 1.20"},
      {:jason, "~> 1.4"},
      {:opentelemetry_exporter, "~> 1.11"},
      {:opentelemetry, "~> 1.7"},
      {:opentelemetry_api, "~> 1.5"},
      {:opentelemetry_bandit, "~> 0.3"},
      {:opentelemetry_experimental, "~> 0.6"},
      {:opentelemetry_api_experimental, "~> 0.6"}
    ]
  end
end
mix deps.get

Keep the releases block. In a mix release the exporter has to be running before the SDK starts. Without applications: [opentelemetry_exporter: :permanent, opentelemetry: :temporary] the exporters fail at boot with inets_not_started. Traces recover after a few seconds and metrics never export.

Configure

The SDK reads these from the process environment, for all three signals.

export OTEL_SERVICE_NAME=my-elixir-service
export OTEL_RESOURCE_ATTRIBUTES="service.version=1.0.0"
export OTEL_EXPORTER_OTLP_ENDPOINT=https://cloud.tracewayapp.com/api/otel
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-project-token"
  • OTEL_EXPORTER_OTLP_ENDPOINT takes the base URL. The exporters append /v1/traces, /v1/metrics and /v1/logs themselves.
  • OTEL_SERVICE_NAME becomes the Server Name on every endpoint, task and issue. Version travels in OTEL_RESOURCE_ATTRIBUTES. A release with neither set reports its release name and version. Once you set the name, set the version too.
  • http/protobuf is already the default. Traceway has no gRPC listener, so never set the protocol to grpc.

Prefer the environment variables over config :opentelemetry_exporter, .... The config form has to be repeated under :opentelemetry_experimental for metrics and logs. With only the first, those two signals go to localhost:4318.

Metrics need one piece of configuration that has no environment variable. Nothing is exported until a reader exists:

config/runtime.exs
import Config
 
config :opentelemetry_experimental,
  readers: [
    %{
      module: :otel_metric_reader,
      config: %{
        export_interval_ms:
          String.to_integer(System.get_env("OTEL_METRIC_EXPORT_INTERVAL", "60000")),
        exporter: {:otel_exporter_metrics_otlp, %{}},
        default_temporality_mapping: %{
          counter: :temporality_delta,
          observable_counter: :temporality_delta,
          histogram: :temporality_delta,
          updown_counter: :temporality_cumulative,
          observable_updowncounter: :temporality_cumulative,
          observable_gauge: :temporality_cumulative
        }
      }
    }
  ]

Counters and histograms send what changed since the last export, and up-down counters and gauges send their current level. List every kind in default_temporality_mapping: the map replaces the defaults, so a kind you leave out becomes cumulative. The SDK itself reads neither OTEL_METRIC_EXPORT_INTERVAL nor the temporality variable. This file reads the interval so you can shorten it while testing.

Start the Instrumentation

lib/demo/application.ex
defmodule Demo.Application do
  use Application
 
  @impl true
  def start(_type, _args) do
    OpentelemetryBandit.setup()
    Demo.RouteAttribute.setup()
 
    :ok =
      :logger.add_handler(:otel_logs, :otel_log_handler, %{
        level: :info,
        exporter: {:otel_exporter_logs_otlp, %{}},
        filters: [drop_conn: {&__MODULE__.drop_conn/2, []}]
      })
 
    Demo.Jobs.setup()
 
    children = [
      {Bandit, plug: Demo.Router, port: String.to_integer(System.get_env("PORT", "4000"))}
    ]
 
    Supervisor.start_link(children, strategy: :one_for_one, name: Demo.Supervisor)
  end
 
  def drop_conn(%{meta: meta} = event, _arg) do
    %{event | meta: Map.drop(meta, [:conn, :crash_reason])}
  end
end

OpentelemetryBandit.setup() creates a SERVER span for every request and records an unhandled exception on it with its stack trace. It does not know your routes, so it names every span after the method alone. This module adds the route:

lib/demo/route_attribute.ex
defmodule Demo.RouteAttribute do
  alias OpenTelemetry.Tracer
 
  def setup do
    :telemetry.attach(
      {__MODULE__, :router_dispatch},
      [:plug, :router_dispatch, :start],
      &__MODULE__.handle_dispatch/4,
      nil
    )
  end
 
  def handle_dispatch(_event, _measurements, %{route: "/*_path"}, _config), do: :ok
 
  def handle_dispatch(_event, _measurements, %{conn: conn, route: route}, _config) do
    Tracer.set_attribute(:"http.route", route)
    Tracer.update_name("#{conn.method} #{route}")
  end
end

Plug.Router announces the matched route in a telemetry event that runs in the request process, so the current span is still the request span. Without this module Traceway has no route to group by and lists every URL as its own endpoint. The first clause skips the catch-all match _, so unknown paths are not grouped under a route named /*_path.

Instrument the Server

lib/demo/router.ex
defmodule Demo.Router do
  use Plug.Router
 
  require Logger
  require OpenTelemetry.Tracer, as: Tracer
 
  plug :match
  plug :dispatch
 
  get "/users/:id" do
    Logger.info("looking up user #{id}")
 
    user =
      Tracer.with_span "load-user" do
        Tracer.set_attribute(:"user.id", id)
        %{id: id, name: "User #{id}"}
      end
 
    conn
    |> put_resp_content_type("application/json")
    |> send_resp(200, Jason.encode!(user))
  end
 
  get "/boom" do
    raise "boom: #{conn.method} #{conn.request_path} failed"
  end
 
  get "/run-job" do
    cleaned = Task.await(Task.async(&Demo.Jobs.cleanup_expired_sessions/0))
 
    conn
    |> put_resp_content_type("application/json")
    |> send_resp(200, Jason.encode!(%{cleaned: cleaned}))
  end
 
  match _ do
    send_resp(conn, 404, "not found")
  end
end
lib/demo/jobs.ex
defmodule Demo.Jobs do
  require OpenTelemetry.Tracer, as: Tracer
  require OpenTelemetryAPIExperimental.Counter, as: Counter
 
  @counter :"app.sessions_cleaned"
 
  def setup do
    Counter.create(@counter, %{description: "Expired sessions removed", unit: :"{session}"})
  end
 
  def cleanup_expired_sessions do
    Tracer.with_span "cleanup-expired-sessions", %{kind: :consumer} do
      cleaned = 7
      Counter.add(@counter, cleaned, %{"job" => "cleanup-expired-sessions"})
      cleaned
    end
  end
end

Run it with the variables from Configure set:

PORT=4000 mix run --no-halt

Keep the match _ clause. Without it every unknown path raises, and each one becomes an Issue.

Exceptions

An unhandled exception in a plug needs no code. opentelemetry_bandit records it on the request span with the Elixir stack trace, the response is a 500, and Traceway shows the Issue next to the failed endpoint row.

For an error you rescue yourself, record it on the current span and set the status:

require OpenTelemetry.Tracer, as: Tracer
 
try do
  charge_card()
rescue
  error ->
    Tracer.record_exception(error, __STACKTRACE__)
    Tracer.set_status(OpenTelemetry.status(:error, Exception.message(error)))
    reraise error, __STACKTRACE__
end

Logs

The :logger.add_handler call in application.ex sends every Logger line of level info and above to Traceway, with the trace and span ids of the process that logged it. Three details:

  • Pass exporter:. The handler's default is the trace exporter, which cannot export logs and prints a bad argument warning every few seconds.
  • Every metadata key becomes a log attribute. Bandit's crash log carries the whole %Plug.Conn{}, request headers included. The drop_conn filter removes it. Add any metadata key of your own that should not leave the process.
  • Export failures are logged at info. With the logger level at warning, a wrong token or a refused connection is invisible. Lower the level while you set this up.

Logs are sent in batches every few seconds, and the stored timestamp is the time of the export, so lines can be a few seconds late and out of order within a batch.

Background Tasks

A job appears under Tasks when its span has kind :consumer. A root span with the default kind is dropped.

Tracer.with_span "cleanup-expired-sessions", %{kind: :consumer} do
  cleanup()
end

The span name is the task name, so keep it stable and put job ids and batch sizes in attributes. OpenTelemetry context belongs to a process. A job that runs in its own process, as it does under Task, Oban or a GenServer, starts without a parent and its span is a root, which is what you want for a task.

Custom Metrics

require OpenTelemetryAPIExperimental.Counter, as: Counter
 
Counter.create(:"app.sessions_cleaned", %{unit: :"{session}"})
Counter.add(:"app.sessions_cleaned", 7, %{"job" => "cleanup-expired-sessions"})

The counter appears in metric discovery as app.sessions_cleaned, with job as a tag you can group by. The reader in config/runtime.exs exports every 60 seconds. While you are checking the integration, set OTEL_METRIC_EXPORT_INTERVAL=5000, and remove it afterwards.

None of these packages records http.server.* metrics, so there is nothing to switch off.

On shutdown the SDK flushes spans. Logs and metrics recorded since the last export are lost.

Phoenix

This guide was checked with Plug and Bandit. For Phoenix, the opentelemetry_phoenix package documents the following, and it was not run for this page:

  • Add {:opentelemetry_phoenix, "~> 2.0"} next to opentelemetry_bandit, and call OpentelemetryBandit.setup() and OpentelemetryPhoenix.setup(adapter: :bandit) in Application.start/2.
  • It sets http.route and the span name from the Phoenix router, so Demo.RouteAttribute is not needed.
  • The endpoint must keep plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint], which generated Phoenix applications have.

Verify It Worked

Start the service, then send a few requests:

curl localhost:4000/users/101
curl localhost:4000/users/102
curl localhost:4000/users/103
curl localhost:4000/boom
curl localhost:4000/run-job

Set the dashboard time picker to the last 15 minutes and check:

  1. Endpoints. One row GET /users/:id with a count of 3, and GET /boom with status 500. Three rows with ids in them means Demo.RouteAttribute.setup() did not run.
  2. Issues. Elixir.RuntimeError: boom: GET /boom failed with its stack trace.
  3. Logs. Three looking up user lines, each linked to its trace.
  4. Tasks. cleanup-expired-sessions.
  5. Metrics. app.sessions_cleaned in metric discovery.

Traces arrive but no metrics? The reader in config/runtime.exs is missing. Nothing at all? Set the logger level to info and look for export failed lines.

Next Steps

  • Traces: how OTel spans map to Endpoints, Tasks and Issues
  • Logs: log record mapping and severity handling
  • Metrics: supported metric types and histogram handling
  • Overview: protocol details, authentication, and a "nothing is showing up" checklist