Packages
Application Monitoring for Elixir: traces, errors (each once, with the code that ran) and logs, sent to Zharp. Phoenix, LiveView, Plug on Bandit or Cowboy, Ecto, Oban, Finch/Req/Tesla and Absinthe, on OpenTelemetry.
Current section
Files
Jump to
Current section
Files
README.md
# Zharp for Elixir
Application Monitoring for Elixir apps: traces, errors and logs, sent to [Zharp](https://zharp.io).
One package for Phoenix (controllers and LiveView), Plug on Bandit or Cowboy, Ecto, Oban, outgoing
HTTP (Finch, Req, Tesla), Absinthe and plain Elixir, built on OpenTelemetry Erlang.
- Requests named by route, continuing the caller's `traceparent`; LiveView mounts and events;
Ecto queries; outgoing HTTP through Finch (Req, Tesla's Finch adapter, Swoosh); Oban jobs;
Absinthe operations. Each switches on when its library is there. Spans you make with
`OpenTelemetry.Tracer` are sent too.
- **Errors, each counted once**, with type (`Ecto.NoResultsError`, not `Elixir.Ecto.NoResultsError`),
message, the stack and the code that ran (the lines around your app's innermost five frames, read
on your server; never Phoenix's or OTP's).
- **Crashes outside requests**: a GenServer, a Task or a supervised process that crashes is an
error with its stack, in the trace of the request that started it.
- **Request and response headers** on the request's span, secrets (authorization, cookies, API
keys, tokens, sessions) as `[REDACTED]`.
- **Failed queries** reported once, with the database, the query (Ecto's are parameterised, so no
values) and the Postgres or MySQL error code; values quoted in database messages are dropped.
- **Jobs in the request's trace**: Oban jobs inserted with `Zharp.Oban.insert/1` run as children of
the request that queued them.
- **Logs**: each console line written during a request ends with ` trace_id=… span_id=…` (two
fields on a LoggerJSON line), so the Zharp agent links it to its request. `ZHARP_LOGS=true` sends
the lines from the SDK instead, where there is no agent.
Elixir 1.16+ and OTP 26+. Phoenix 1.7+.
## Phoenix
```sh
mix igniter.install zharp
```
That adds the dependency, `plug Zharp.Plug` to your endpoint, `config :zharp` to
`config/runtime.exs` and the release step to `mix.exs`. Then set your key, from **Settings →
Applications** in Zharp:
```sh
ZHARP_KEY=zpk_… mix phx.server
```
`npm init zharp` does the same from a terminal (it runs Igniter when your project has it).
### Without Igniter
```elixir
# mix.exs
{:zharp, "~> 0.1"}
```
```elixir
# lib/my_app_web/endpoint.ex, before plug Plug.RequestId
plug Zharp.Plug
```
and `ZHARP_KEY` in the environment. That's all: Zharp starts with your app, before the endpoint.
## Plug (no Phoenix)
The dependency, `ZHARP_KEY`, and the plug at the top of your router:
```elixir
defmodule MyApp.Router do
use Plug.Router
plug Zharp.Plug
plug :match
plug :dispatch
end
```
Spans are named by the route (`GET /orders/:id`), on Bandit or Cowboy.
## Elixir: scripts, workers
The dependency and `ZHARP_KEY`. Crashing processes are reported by themselves; report what you
rescue with `Zharp.capture_exception/2`. At the end of a script, `Zharp.flush()` sends what's queued.
## Releases: the code that ran
A `mix release` ships compiled `.beam` files, not your `.ex` sources. Add the release step (the
installer does) and the release carries your `lib/`, read on your server when an error happens.
Nothing is uploaded.
```elixir
# mix.exs
releases: [
my_app: [steps: [:assemble, &Zharp.Release.package_source/1]]
]
```
Keep it after `:assemble` and before `:tar`. In development (`mix phx.server`) the files are read
from disk and need nothing.
Which frames are your code is decided by OTP application, not by path (Phoenix's frames are
`lib/phoenix/…` just like yours): your project's applications, an umbrella's included, are sent
with each error. Set `config :zharp, in_app: [:my_app, :my_app_web]` to choose them yourself.
## Settings
Every setting can be set in `config/runtime.exs` (`config :zharp, key: …`) or the environment.
Config wins over the environment.
| `config :zharp` | Environment | Default |
|---|---|---|
| `key:` | `ZHARP_KEY` | none: nothing is sent without one |
| `service:` | `ZHARP_SERVICE`, `OTEL_SERVICE_NAME` | your app's name |
| `environment:` | `ZHARP_ENVIRONMENT` | `Mix.env()` when Mix is there |
| `release:` | `ZHARP_RELEASE` | none |
| `endpoint:` | `ZHARP_ENDPOINT` | `https://api.zharp.io/api/v1/otlp` |
| `sample_rate:` | `ZHARP_SAMPLE_RATE` | `1.0` (traces with an error are always kept) |
| `logs:` | `ZHARP_LOGS` | `false` |
| `log_level:` | `ZHARP_LOG_LEVEL` | `:info` (with `logs: true`) |
| `log_correlation:` | `ZHARP_LOG_CORRELATION` | `true` |
| `capture_headers:` | `ZHARP_CAPTURE_HEADERS` | on; `[redact: ["x-tenant"]]` filters more names |
| `capture_query_errors:` | `ZHARP_CAPTURE_QUERY_ERRORS` | `true` |
| `capture_source_context:` | `ZHARP_CAPTURE_SOURCE_CONTEXT` | `true` |
| `capture_crashes:` | `ZHARP_CAPTURE_CRASHES` | `true` |
| `tracing:` | `ZHARP_TRACING` | `true`; `false` sends errors and logs only |
| `in_app:` | none | your project's applications |
| `enabled: false` | `ZHARP_DISABLED=true` | turns everything off (the installer sets it for tests) |
Traces go to `<endpoint>/v1/traces` as OTLP http/protobuf, gzipped, with `Authorization: Bearer
<key>`; logs and errors outside a span to `<endpoint>/v1/logs`. Zharp sets the exporter of
OpenTelemetry's default batch processor at startup, so `config :opentelemetry` needs nothing. If
you configure your own `:processors`, add `{:otel_batch_processor, %{exporter: {Zharp.Exporter,
Zharp.options()}}}` yourself.
## API
```elixir
Zharp.capture_exception(error, stacktrace: __STACKTRACE__, extra: %{order_id: 42}) # rescued, as handled
Zharp.set_user(id: user.id, email: user.email) # on the request's span, logs and errors, and its Tasks
Zharp.set_tag("tenant", "acme") # on every log and error from now on
Zharp.log(:info, "order paid", order_id: 42) # a log line sent from the SDK, whatever ZHARP_LOGS says
Zharp.flush() # send what's queued now (end of a script)
```
Spans of your own, with OpenTelemetry's API:
```elixir
require OpenTelemetry.Tracer, as: Tracer
Tracer.with_span "render invoice" do
render(invoice)
end
```
A browser or mobile app using a Zharp SDK sends its user and session with each request (W3C
`baggage`); `Zharp.Plug` puts them on the request's span.
### Oban
Oban has no hook for changing a job as it is inserted. To run a job in the trace of the request
that queued it, insert it through Zharp:
```elixir
MyApp.Workers.Receipt.new(%{order_id: order.id}) |> Zharp.Oban.insert()
```
(or `Zharp.Oban.with_trace(changeset)` before your own insert). Every job is a span either way, and
a job that raises is an error.
### Outgoing HTTP
Calls through Finch (Req, Tesla with its Finch adapter, Swoosh) are spans with nothing to add. To
carry the trace to the service you call, so its spans join yours:
```elixir
req = Req.new(base_url: "https://billing.internal") |> Zharp.Req.attach()
```
```elixir
# a Tesla client
plug Zharp.Tesla
```
## What is reported
- An exception that escapes a request, a LiveView callback or an Oban job: unhandled, on that span.
- A process that crashes (GenServer, Task, supervised process): unhandled, from its crash report.
Reports of Bandit's and Cowboy's request processes are skipped (the request's span has them),
and so is an exit with reason `:normal`, `:shutdown` or `{:shutdown, _}`.
- `Zharp.capture_exception/2`: handled.
- A failed query the app handled: handled, where the app ran it. Constraint violations your
changesets turn into form errors (`unique_constraint`…) aren't reported.
- Not reported: exceptions Plug answers with a status below 500 (`Phoenix.Router.NoRouteError`,
`Ecto.NoResultsError`, `Phoenix.ActionClauseError`). They stay on the request's span.
## Development
Everything runs in Docker (official `elixir` images, Postgres, MySQL):
```sh
e2e/unit.sh # mix test, database tests included, on Elixir 1.16/OTP 26 and 1.20/OTP 29
scripts/mix.sh 1.20-otp-29 test test/servers_test.exs
```
`e2e/` also has end-to-end apps (Phoenix 1.8 on Bandit as a release with Postgres, Phoenix 1.7 on
Cowboy with MySQL, a Plug app, an umbrella, a script, `ZHARP_LOGS`) sending to a stand-in OTLP
receiver: `node e2e/run.mjs <case>`.
## License
MIT