Sign Up
Open in ChatGPT Open in Claude Open in Perplexity

Phoenix SDK Guide

The monoscope Phoenix SDK is a Plug that records incoming requests and sends them to monoscope. This guide shows how to install and configure it.


Prerequisites

You need a monoscope project and its API key. If you do not have them yet, follow Get started.

Set Up With Your Coding Agent

Your coding agent can add the instrumentation for you. Install the monoscope skills and the monoscope CLI:

# Claude Code
claude plugin marketplace add monoscope-tech/skills
claude plugin install monoscope-skills@monoscope-skills

# Cursor, Codex, Cline and other agents
npx skills add monoscope-tech/skills

# monoscope CLI
curl https://monoscopehq.com/install.sh | sh
monoscope auth login

Then ask your agent to instrument the project. In Claude Code, run:

/monoscope-skills:instrument Add OpenTelemetry for monoscope to this project

The skill uses the CLI to add the SDK and to make sure that events arrive. To do the setup by hand, follow the steps below. For help from a person, email us.

Installation

Add apitoolkit_phoenix to the dependencies in your mix.exs file:

def deps do
  [
    {:apitoolkit_phoenix, "~> 0.1.2"}
  ]
end

Then run mix deps.get to install it.

Configuration

Import the ApitoolkitPhoenix Plug in your router.ex file and add it to your pipeline:

defmodule HelloWeb.Router do
  use HelloWeb, :router
  use Plug.ErrorHandler
  import ApitoolkitPhoenix

  pipeline :api do
    plug :accepts, ["json"]
    plug ApitoolkitPhoenix,
      config: %{
        api_key: "YOUR_API_KEY",
        debug: false,
      }
    # Other plugs...
  end
end

Only api_key is required. These fields are optional:

Option Description
debug Set to true to enable debug mode.
redact_headers A list of HTTP header keys to redact. authorization, cookie, set-cookie and proxy-authorization are always redacted.
redact_request_body A list of JSONPaths from the request body to redact.
redact_response_body A list of JSONPaths from the response body to redact.
root_url The monoscope API URL. Defaults to https://app.apitoolkit.io.

Tip

Replace YOUR_API_KEY with an API key from Settings > API Keys in monoscope.

Redacting Sensitive Data

<div class=”callout”> <i class=”fa-solid fa-circle-info”></i> <p><code>authorization</code>, <code>cookie</code>, <code>set-cookie</code> and <code>proxy-authorization</code> headers are always redacted, on requests and responses and on outgoing calls, whatever you configure. Header names match case-insensitively.</p> </div>

If you have fields that are sensitive and should not be sent to monoscope servers, you can mark those fields to be redacted (the fields will never leave your servers).

To mark a field for redacting via this SDK, you need to provide additional arguments to the config key with paths to the fields that should be redacted. There are three arguments you can provide to configure what gets redacted, namely:

  1. redact_headers: A list of HTTP header keys.
  2. redact_request_body: A list of JSONPaths from the request body.
  3. redact_response_body: A list of JSONPaths from the response body.

JSONPath is a query language used to select and extract data from JSON files. For example, given the following sample user data JSON object:

{
  "user": {
    "name": "John Martha",
    "email": "[email protected]",
    "addresses": [
      {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA",
        "zip": "12345"
      },
      {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA",
        "zip": "12345"
      }
    ],
    "credit_card": {
      "number": "4111111111111111",
      "expiration": "12/28",
      "cvv": "123"
    }
  }
}

Examples of valid JSONPath expressions would be:

JSONPath Description
$.user.addresses[*].zip In this case, monoscope will replace the zip field in all the objects of the addresses list inside the user object with the string [CLIENT_REDACTED].
$.user.credit_card In this case, monoscope will replace the entire credit_card object inside the user object with the string [CLIENT_REDACTED].

Tip

To learn more about JSONPaths, please take a look at the official docs or use this JSONPath Evaluator to validate your JSONPath expressions.

You can also use our JSON Redaction Tool to preview what the final data sent from your API to monoscope will look like, after redacting any given JSON object.


Here’s an example of what the configuration would look like with redacted fields:

defmodule HelloWeb.Router do
  use HelloWeb, :router
  use Plug.ErrorHandler
  import ApitoolkitPhoenix

  pipeline :api do
    plug :accepts, ["json"]
    # Other plugs
    plug ApitoolkitPhoenix,
      config: %{
        api_key: "YOUR_API_KEY",
        redact_headers: ["content-type", "Authorization", "HOST"],
        redact_request_body: ["$.user.email", "$.user.addresses"],
        redact_response_body: ["$.users[*].email", "$.users[*].credit_card"]
      }
  end
end

Note

  • The redact_headers config field expects a list of case-insensitive headers as strings.
  • The redact_request_body and redact_response_body config fields expect a list of JSONPaths as strings.
  • The list of items to be redacted will be applied to all endpoint requests and responses on your server.

Error Reporting

With monoscope, you can track and report different unhandled or uncaught errors, API issues, and anomalies at different parts of your application. This will help you associate more detail and context from your backend with any failing customer request.

To report all uncaught errors, call `report_error()` with the `conn` and the error in your `handle_errors` function:
@impl Plug.ErrorHandler
def handle_errors(conn, err) do
  conn = report_error(conn, err)
  json(conn, %{message: "Something went wrong!"})
end
To report a specific error, call `report_error()` in a controller with the `conn`, the error and `__STACKTRACE__`. It returns the updated `conn`, so keep using that `conn`:
defmodule HelloWeb.PageController do
  use HelloWeb, :controller
  import ApitoolkitPhoenix

  def home(conn, _params) do
    conn =
      try do
        raise("Oops, something went wrong!")
      rescue
        err ->
          # Report the error to monoscope
          report_error(conn, err, __STACKTRACE__)
      end

    json(conn, %{message: "Hello, world!"})
  end
end

Non-HTTP Entry Points (Background Jobs, Workers, CLIs)

The Phoenix plug only covers HTTP requests. Oban workers, Broadway pipelines, GenServer pollers, and Mix tasks are invisible until you wrap each handler in a span yourself. Always cover these alongside your HTTP routes.

The examples below use OpenTelemetry, not the Phoenix SDK. Add the opentelemetry and opentelemetry_exporter dependencies, then point the exporter at monoscope:

OTEL_EXPORTER_OTLP_ENDPOINT="http://otelcol.monoscope.tech:4318"
OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf"
OTEL_RESOURCE_ATTRIBUTES="x-api-key=YOUR_API_KEY"
OTEL_SERVICE_NAME="my-service"

For Oban, use the official auto-instrumentation — every job automatically gets a span:

# mix.exs
{:opentelemetry_oban, "~> 1.1"}

# application.ex — in start/2 before children:
OpentelemetryOban.setup()

For Broadway, GenServer pollers, and Mix tasks, wrap each handler with OpenTelemetry.Tracer:

require OpenTelemetry.Tracer, as: Tracer

def process_email(payload) do
  Tracer.with_span "email.send", %{
    kind: :consumer,
    attributes: [
      {"messaging.system", "broadway"},
      {"messaging.operation", "process"},
      {"messaging.destination.name", "emails"},
      {"code.function", "MyApp.Worker.process_email"}
    ]
  } do
    try do
      send_email(payload)
    rescue
      e ->
        Tracer.record_exception(e, __STACKTRACE__)
        Tracer.set_status(:error, Exception.message(e))
        reraise e, __STACKTRACE__
    end
  end
end

For Mix tasks and other one-shot processes, call :opentelemetry.get_tracer_provider() |> :otel_tracer_provider.force_flush() before exit so the BatchSpanProcessor flushes; otherwise spans are dropped silently.

Next Steps


Explore the Phoenix SDK