TraceGuard
When a Phoenix request fails, TraceGuard gives you a redacted diagnostic report for that one request: the route, the Ecto queries it ran (in order, with timings), the work it did in Tasks and GenServer calls you opted in, the exception, and what TraceGuard could not see. It never changes the response or swallows the exception.
Status: 0.1.0, an early release on Hex. Before 1.0, APIs marked experimental (GenServer propagation and the storage adapters) can change in a minor version; every change is listed in the changelog. There's no production use yet. Tested in CI on Elixir 1.15.8 / OTP 26 to Elixir 1.20.1 / OTP 29, Phoenix 1.7 and 1.8, Bandit and Cowboy, and PostgreSQL 16 and 18, on Linux only. See Limitations and docs/compatibility.md.
Feedback is welcome, especially on integration friction, the database migration experience and compatibility: open an issue.
Why not just logs or telemetry?
- Logs interleave every concurrent request, and they include raw secrets. Finding "what did this failing request do" means correlating lines by hand.
- Telemetry emits events, but nothing ties them back into one failed request's story, and nothing redacts them.
- TraceGuard attaches to the telemetry Phoenix and Ecto already emit. It attributes each event to the request that caused it (by process, never by timing) and keeps only failures. It produces one JSON document per failure with sensitive keys redacted before the report leaves the request process. It is a library in your app: no agent, no service, no network calls.
It is not a distributed tracer or an APM, and it doesn't trace function calls. It records the events listed in the report, nothing more.
Install
# mix.exs
{:trace_guard, "~> 0.1.0"}
mix deps.get
~> 0.1.0 accepts patch releases (0.1.x) but not 0.2, which may change
experimental APIs. For the optional adapters, see Storage:
SQLite needs {:exqlite, "~> 0.42"}; Ecto/PostgreSQL uses the ecto_sql
and postgrex your application already has.
Configure (three lines)
# lib/my_app_web/endpoint.ex: after Plug.RequestId, before Plug.Telemetry
plug Plug.RequestId
plug TraceGuard.Plug
plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
# config/config.exs
config :trace_guard, ecto_telemetry_prefixes: [[:my_app, :repo]] # for MyApp.Repo
Everything else has conservative defaults: no request bodies, query strings, cookies, SQL text or SQL parameters. See docs/configuration.md.
End-to-end example
# A controller action that fails after a query
def show(conn, %{"id" => id}) do
order = Repo.get!(Order, id)
Payments.charge!(order) # raises "payment provider rejected charge (api_key=demo_key_123)"
json(conn, order)
end
$ curl -i localhost:4000/api/orders/7
HTTP/1.1 500 Internal Server Error
x-traceguard-id: 9a172de8c3a49cac179676daf5950dca
{"errors":{"detail":"Internal Server Error"}}
iex> {:ok, report} = TraceGuard.await_report("9a172de8c3a49cac179676daf5950dca")
iex> report["failure"]["message"]
"payment provider rejected charge (api_key=[REDACTED])"
iex> for e <- report["events"], do: {e["offset_us"], e["process"], e["name"]}
[{25, "request", "request.start"}, {10684, "request", "phoenix.router_dispatch.start"},
{26715, "request", "ecto.query"}, ..., {127893, "request", "phoenix.router_dispatch.exception"}, ...]
iex> TraceGuard.export_json("9a172de8c3a49cac179676daf5950dca", pretty: true)
{:ok, "{\n \"schema\": \"traceguard.report/v1\", ..."}
(Abridged and illustrative.) Real, complete reports from the demo: request failure, failure in a Task, failure in a traced GenServer call.
Retrieving reports
| You have | Use |
|---|---|
the x-traceguard-id response header |
TraceGuard.get_report(id) or TraceGuard.await_report(id, timeout) |
| no header (throws, exits, endpoint-plug failures) | the client's correlation ID (incoming_header: "x-correlation-id"), then TraceGuard.list_reports(incoming_id: "..."); or the request ID from your logs, list_reports(request_id: ...) |
| a trace ID, and want to know what happened to its report | TraceGuard.report_status(id): :stored, {:dropped, reason}, :pending or :unknown |
| a report to share | TraceGuard.export_json(id, pretty: true) |
Where reports are kept:
| Storage | Use it for | Survives restarts | Needs |
|---|---|---|---|
| Memory (default) | trying TraceGuard, development, apps that only need recent failures | no | nothing |
| SQLite | local development and tests where reports should outlive a restart | yes | {:exqlite, "~> 0.42"} and a file path |
| Ecto/PostgreSQL (experimental) | apps already on PostgreSQL that want reports in their own database | yes | your existing Repo, plus an explicit migration |
The Ecto adapter uses your existing Repo (no second Repo, pool or
database):
config :trace_guard, storage: {TraceGuard.Storage.Ecto, repo: MyApp.Repo}.
Its table comes from a migration you generate and run yourself:
mix trace_guard.gen.ecto_migration && mix ecto.migrate. TraceGuard never
runs migrations or changes your schema on its own.
Storage is bounded on purpose. A burst beyond max_pending_reports, or a
storage failure (a database outage, a missing table), drops reports,
and each drop is recorded (report_status/1, report_stats/0, telemetry).
See docs/storage.md. All lookups are node-local
functions; TraceGuard serves nothing over HTTP.
Work outside the request process (opt-in)
Task.async(TraceGuard.wrap(fn -> Repo.all(Product) end)) # Task
TraceGuard.call(MyApp.Pricing, {:quote, sku, qty}) # GenServer with `use TraceGuard.Server`
Unwrapped Tasks, ordinary GenServer.call/3s, casts and a server's
background work are never attributed to a request. See
task propagation and
GenServer propagation (experimental).
What is captured and what is redacted
- Captured: method, route template, status, timings; Phoenix endpoint and router events; Ecto query timing, table, row count, outcome and calling function; allow-listed request headers; exception module, message and stack frames (without arguments); opted-in Task and GenServer lifecycle events.
- Never captured: request bodies, query strings, cookies, SQL parameters, result rows, Task or GenServer arguments, inspected throw values or exit reasons.
- Redacted before storage or export: values under sensitive keys
(
password,authorization,token,api_key,secret,cookie, ... and yourredact_keys), recursively. Also labelled secrets in exception messages (api_key=…,Bearer …). - Not protected: unlabelled secrets inside exception messages
(
capture_exception_message: falseturns messages off), and your application's own logs.
⚠️ TraceGuard does not sanitize Phoenix, Plug, Bandit, Cowboy, Ecto or OTP log output. Those log raw exception messages, secrets included, exactly as they would without TraceGuard. Verified: in the external integration test, both Bandit's and Cowboy's crash logs contained the API key that the TraceGuard report had redacted.
Details: docs/security.md.
Reproduce the demo
cd demo
mix setup && mix phx.server # http://localhost:4000
./scripts/run_demo.sh a.json b.json c.json # in another terminal
The script triggers three deliberate failures: in the request, in a Task, and in a GenServer call. It exports their reports and checks that none of seven planted secrets appear in them. See demo/README.md.
Limitations
- Only observable, attributable events. Events must come from the
request process, a
wrap/1ped function, or aTraceGuard.Servercallback duringTraceGuard.call/3. No function tracing, no implicit propagation, single node only. - Some failures have no response header: throws, exits and exceptions in endpoint plugs. Use correlation IDs (above).
- Cowboy: an exception raised in an endpoint plug (outside the router)
can go unreported, because Cowboy terminates the request process right
after the response, before TraceGuard can finish. This is reproduced by a
test that kills the request process at that point, but wasn't observed
under real Cowboy. Router failures,
including throws and exits, are reported. Cowboy's crash log doesn't carry
trace_guard_id. Current Cowboy needs OTP 27 or later. debug_errors: true: failures outside the router are not reported.- Exceptions after the response was sent are not reported.
- Storage: in memory (lost on restart), SQLite (development and
testing), or your PostgreSQL through your Ecto Repo (experimental;
verified on PostgreSQL 16 and 18). One writer stores reports one at a
time: about 180 reports per second on PostgreSQL on the test laptop, and
far fewer while the database is unreachable (each failed write waits for
your pool, about 4 s there). Reports beyond
max_pending_reportsare refused and recorded as dropped (:overloaded), not queued; during an outage, most drops look like that, andreport_stats().last_errortells you the cause. Deleting reports from PostgreSQL is logical: copies can remain in WAL, replicas and backups. - Untested: PostgreSQL versions other than 16 and 18, managed or pooled PostgreSQL (TLS, PgBouncer), macOS, Windows, releases, multiple nodes, long-running load. See docs/compatibility.md.
- Performance has been measured on one laptop only. Observations, not guarantees, are in docs/performance.md.
Development
mix test # library (177 tests + 1 doctest; the 21 PostgreSQL tests are excluded without a server)
(cd demo && mix test) # demo application (16 tests)
scripts/compat_matrix.sh # library on several Elixir/OTP/dependency versions
scripts/external_smoke.sh # a fresh Phoenix app integrating TraceGuard (Bandit/Cowboy x memory/SQLite)
eval "$(scripts/local_postgres.sh start | tail -1)" # a user-local PostgreSQL (or set TRACE_GUARD_POSTGRES_URL)
mix test # now also runs the real PostgreSQL suite
scripts/external_postgres_smoke.sh # a fresh Phoenix app installs TraceGuard on PostgreSQL and migrates
scripts/no_ecto_smoke.sh # a fresh Phoenix app without Ecto (optional dependencies stay optional)
scripts/package_check.sh # what the Hex package would contain (builds locally, publishes nothing)
MIX_ENV=dev mix docs # HexDocs-style documentation in doc/
CI (GitHub Actions, .github/workflows/) is configured to run these checks
on every pull request, with real PostgreSQL 16 and 18 services, and a
weekly workflow for the other toolchain rows and Cowboy. See docs/compatibility.md.
How to contribute is in CONTRIBUTING.md, the release procedure in docs/release_checklist.md, the history in CHANGELOG.md, and design notes in docs/architecture.md and the phase reviews.
License
Apache License 2.0. See LICENSE.