# `TraceGuard.Plug`
[🔗](https://github.com/HataluliRandima/trace_guard/blob/v0.1.0/lib/trace_guard/plug.ex#L1)

Starts a TraceGuard trace for each request.

Add it to your endpoint **after** `Plug.RequestId` (so the request ID can be
recorded) and **before** `Plug.Telemetry` and your router:

    plug Plug.RequestId
    plug TraceGuard.Plug
    plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
    ...
    plug MyAppWeb.Router

## What it does

* Generates a fresh 128-bit trace ID and stores a request context in the
  current process (see `TraceGuard.Context`).
* Records method, start time, allow-listed request headers, the
  `x-request-id` set by `Plug.RequestId` and, when configured, a
  validated incoming correlation ID and the request path. Query strings,
  bodies and cookies are never read.
* Adds `trace_guard_id` to `Logger` metadata and, by default, an
  `x-traceguard-id` response header.
* Registers a `before_send` callback that records the response status and
  completes the trace.

## What it does not do

A plain Plug **cannot** observe exceptions raised by downstream plugs: it
returns its conn before the router runs. Exceptions are therefore captured
through Phoenix telemetry (`[:phoenix, :router_dispatch, :exception]` and
`[:phoenix, :error_rendered]`) by `TraceGuard.Telemetry`. This plug never
rescues, so your application's error handling is unchanged.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
