
Sentry Elixir Sdk
- 1.6k installs
- 243 repo stars
- Updated July 27, 2026
- getsentry/sentry-for-ai
Complete Sentry SDK setup for Elixir: error monitoring, logging, tracing, crons. Detects project deps, recommends baseline + optional features, guides Igniter installer or manual config, verifies with test event.
About
The Sentry Elixir SDK is an opinionated installer and configuration guide for complete error monitoring in Elixir, Phoenix, and Plug applications. Developers use it to capture unhandled exceptions, forward crash reports via LoggerHandler, trace HTTP requests and database queries through OpenTelemetry, and detect silent failures in scheduled jobs (Oban, Quantum, GenServer). The skill detects existing dependencies, recommends baseline (error monitoring + logging) and optional features (tracing, crons, Sentry Logs), and walks through either the Igniter interactive installer or manual setup in mix.exs, config/config.exs, and lib/my_app/application.ex. Includes Phoenix endpoint and LiveView hooks, runtime config for DSN/release, and verification via mix sentry.send_test_event.
- Detect Elixir version, Phoenix, LiveView, Oban, Quantum, and OpenTelemetry in mix.exs; skip install if Sentry already pr
- Always recommend error monitoring + logging; propose tracing (if Phoenix/Ecto/OTel detected) and crons (if Oban/Quantum
- Igniter installer (sentry v11.0.0+) auto-configures config/ files and Application.start/2; manual setup in 5 steps if sk
- Add Sentry.PlugCapture (Cowboy only) and Sentry.PlugContext to endpoint; add Sentry.LiveViewHook to live_view macro for
- Verify with mix sentry.send_test_event; cross-link to React/Next.js/Svelte SDK if frontend directory detected for distri
Sentry Elixir Sdk by the numbers
- 1,601 all-time installs (skills.sh)
- +41 installs in the week ending Jul 28, 2026 (Skillselion tracking)
- Ranked #298 of 4,386 Backend & APIs skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Jul 28, 2026 (Skillselion catalog sync)
sentry-elixir-sdk capabilities & compatibility
Sentry free tier; pay-as-you-grow after 10k events/month
- Capabilities
- detect elixir project dependencies and versions · guide igniter installer or manual sdk setup · configure error monitoring, logging, tracing, cr · generate config/config.exs and runtime.exs snipp · add phoenix plugs and liveview hooks · verify sdk with test event · cross link frontend sdks for distributed tracing · troubleshoot missing events, stack traces, conte
- Works with
- sentry
- Use cases
- debugging
- Platforms
- macOS · Windows · Linux · WSL
- Runs
- Remote server
- Pricing
- Free
npx skills add https://github.com/getsentry/sentry-for-ai --skill sentry-elixir-sdkAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1.6k |
|---|---|
| repo stars | ★ 243 |
| Security audit | 3 / 3 scanners passed |
| Last updated | July 27, 2026 |
| Repository | getsentry/sentry-for-ai ↗ |
What it does
Configure error monitoring, tracing, logging, and cron tracking in Elixir and Phoenix applications via Sentry SDK.
Who is it for?
Teams running Phoenix/Plug applications who need centralized error monitoring, request tracing, and scheduled job observability.
Skip if: Pure command-line CLI tools; serverless functions (use platform-specific SDKs); applications without HTTP or job scheduling.
When should I use this skill?
User asks to 'add Sentry to Elixir', 'set up Sentry', 'install sentry hex package', or configure error monitoring/tracing/logging/crons in Elixir or Phoenix.
What you get
Error events and logs stream to Sentry dashboard; tracing shows HTTP-to-database request flow; cron failures surface with stack traces; distributed tracing connects Phoenix backend to JavaScript frontend.
- Sentry dependency in mix.exs
- config/config.exs with dsn, environment_name, in_app_otp_apps
- config/runtime.exs with SENTRY_DSN and release
By the numbers
- Sentry Elixir SDK v13.2.0 requires Elixir ~> 1.13
- Igniter installer available since sentry v11.0.0
- Default max_breadcrumbs is 100 per process
Files
All Skills > SDK Setup > Elixir SDK
Sentry Elixir SDK
Opinionated wizard that scans your Elixir project and guides you through complete Sentry setup.
Invoke This Skill When
- User asks to "add Sentry to Elixir" or "set up Sentry" in an Elixir or Phoenix app
- User wants error monitoring, tracing, logging, or crons in Elixir or Phoenix
- User mentions
sentryhex package,getsentry/sentry-elixir, or Elixir Sentry SDK - User wants to monitor exceptions, Plug errors, LiveView errors, or scheduled jobs
Note: SDK versions and APIs below reflect Sentry docs at time of writing (sentry v13.2.0, requires Elixir ~> 1.13).
Always verify against docs.sentry.io/platforms/elixir/ before implementing.
---
Phase 1: Detect
Run these commands to understand the project before making any recommendations:
# Check existing Sentry dependency
grep -i sentry mix.exs 2>/dev/null
# Detect Elixir version
cat .tool-versions 2>/dev/null | grep elixir
grep "elixir:" mix.exs 2>/dev/null
# Detect Phoenix or Plug
grep -E '"phoenix"|"plug"' mix.exs 2>/dev/null
# Detect Phoenix LiveView
grep "phoenix_live_view" mix.exs 2>/dev/null
# Detect Oban (job queue / crons)
grep "oban" mix.exs 2>/dev/null
# Detect Quantum (cron scheduler)
grep "quantum" mix.exs 2>/dev/null
# Detect OpenTelemetry usage
grep "opentelemetry" mix.exs 2>/dev/null
# Check for companion frontend
ls assets/ frontend/ web/ client/ 2>/dev/nullWhat to note:
| Signal | Impact |
|---|---|
sentry already in mix.exs? | Skip install; go to Phase 2 (configure features) |
| Phoenix detected? | Add Sentry.PlugCapture, Sentry.PlugContext, optionally Sentry.LiveViewHook |
| LiveView detected? | Add Sentry.LiveViewHook to the live_view macro in my_app_web.ex |
| Oban detected? | Recommend Crons + error capture via Oban integration |
| Quantum detected? | Recommend Crons via Quantum integration |
| OpenTelemetry already present? | Tracing setup only needs Sentry.OpenTelemetry.* config |
| Frontend directory found? | Trigger Phase 4 cross-link suggestion |
---
Phase 2: Recommend
Based on what you found, present a concrete recommendation. Don't ask open-ended questions — lead with a proposal:
Recommended (core coverage):
- ✅ Error Monitoring — always; captures exceptions and crash reports
- ✅ Logging —
Sentry.LoggerHandlerforwards crash reports and error logs to Sentry - ✅ Tracing — if Phoenix, Plug, or Ecto detected (via OpenTelemetry)
Optional (enhanced observability):
- ⚡ Crons — detect silent failures in scheduled jobs (Oban, Quantum, or manual GenServer)
- ⚡ Sentry Logs — forward structured logs to Sentry Logs Protocol (sentry v12.0.0+)
Recommendation logic:
| Feature | Recommend when... |
|---|---|
| Error Monitoring | Always — non-negotiable baseline |
| Logging | Always — LoggerHandler captures crashes that aren't explicit capture_exception calls |
| Tracing | Phoenix, Plug, Ecto, or OpenTelemetry imports detected |
| Crons | Oban, Quantum, or periodic GenServer/Task patterns detected |
| Sentry Logs | sentry v12.0.0+ in use and structured log search is needed |
Propose: "I recommend setting up Error Monitoring + Logging [+ Tracing if Phoenix/Ecto detected]. Want me to also add Crons or Sentry Logs?"
---
Phase 3: Guide
Option 1: Igniter Installer (Recommended)
You need to run this yourself — the Igniter installer requires interactive terminal input that the agent can't handle. Copy-paste into your terminal:
>
```bash
mix igniter.install sentry
```
>
Available since sentry v11.0.0. It auto-configuresconfig/config.exs,config/prod.exs,config/runtime.exs, andlib/my_app/application.ex.
>
Once it finishes, come back and skip to [Verification](#verification).
If the user skips the Igniter installer, proceed with Option 2 (Manual Setup) below.
---
Option 2: Manual Setup
Install
Add to mix.exs dependencies:
# mix.exs
defp deps do
[
{:sentry, "~> 13.0"},
{:finch, "~> 0.21"}
# Add jason if using Elixir < 1.18:
# {:jason, "~> 1.4"},
]
endmix deps.getConfigure
# config/config.exs
config :sentry,
dsn: System.get_env("SENTRY_DSN"),
environment_name: config_env(),
enable_source_code_context: true,
root_source_code_paths: [File.cwd!()],
in_app_otp_apps: [:my_app]For runtime configuration (recommended for DSN and release):
# config/runtime.exs
import Config
config :sentry,
dsn: System.fetch_env!("SENTRY_DSN"),
release: System.get_env("SENTRY_RELEASE", "my-app@#{Application.spec(:my_app, :vsn)}")Quick Start — Recommended Init Config
This config enables the most features with sensible defaults:
# config/config.exs
config :sentry,
dsn: System.get_env("SENTRY_DSN"),
environment_name: config_env(),
enable_source_code_context: true,
root_source_code_paths: [File.cwd!()],
in_app_otp_apps: [:my_app],
# Logger handler config — captures crash reports
logger: [
{:handler, :sentry_handler, Sentry.LoggerHandler, %{
config: %{
metadata: [:request_id],
capture_log_messages: true,
level: :error
}
}}
]Activate Logger Handler
Add Logger.add_handlers/1 in Application.start/2:
# lib/my_app/application.ex
def start(_type, _args) do
Logger.add_handlers(:my_app) # activates the :sentry_handler configured above
children = [
MyAppWeb.Endpoint
# ... other children
]
Supervisor.start_link(children, strategy: :one_for_one)
endPhoenix Integration
`lib/my_app_web/endpoint.ex`
defmodule MyAppWeb.Endpoint do
use Sentry.PlugCapture # Add ABOVE use Phoenix.Endpoint (Cowboy adapter only)
use Phoenix.Endpoint, otp_app: :my_app
# ...
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
plug Sentry.PlugContext # Add BELOW Plug.Parsers
# ...
endNote:Sentry.PlugCaptureis only needed for the Cowboy adapter. Phoenix 1.7+ defaults to Bandit, wherePlugCaptureis harmless but unnecessary.Sentry.PlugContextis always recommended — it enriches events with HTTP request data.
LiveView errors — `lib/my_app_web.ex`
def live_view do
quote do
use Phoenix.LiveView
on_mount Sentry.LiveViewHook # captures errors in mount/handle_event/handle_info
end
endPlain Plug Application
defmodule MyApp.Router do
use Plug.Router
use Sentry.PlugCapture # Cowboy only
plug Plug.Parsers, parsers: [:urlencoded, :multipart]
plug Sentry.PlugContext
# ...
endFor Each Agreed Feature
Walk through features one at a time. Load the reference file for each, follow its steps, and verify before moving to the next:
| Feature | Reference file | Load when... |
|---|---|---|
| Error Monitoring | ${SKILL_ROOT}/references/error-monitoring.md | Always (baseline) |
| Tracing | ${SKILL_ROOT}/references/tracing.md | Phoenix / Ecto / OpenTelemetry detected |
| Logging | ${SKILL_ROOT}/references/logging.md | LoggerHandler or Sentry Logs setup |
| Crons | ${SKILL_ROOT}/references/crons.md | Oban, Quantum, or periodic jobs detected |
For each feature: Read ${SKILL_ROOT}/references/<feature>.md, follow steps exactly, verify it works.
---
Configuration Reference
Key Config Options
| Option | Type | Default | Purpose |
|---|---|---|---|
:dsn | `string \ | nil` | nil |
:environment_name | `atom \ | string` | "production" |
:release | `string \ | nil` | nil |
:sample_rate | float | 1.0 | Error event sample rate (0.0–1.0) |
:enable_source_code_context | boolean | false | Include source lines around errors |
:root_source_code_paths | [path] | [] | Required when source context is enabled |
:in_app_otp_apps | [atom] | [] | OTP apps whose modules are "in-app" in stacktraces |
:before_send | `(event -> event \ | nil) \ | {m, f}` |
:after_send_event | `(event, result -> any) \ | {m, f}` | nil |
:filter | module | Sentry.DefaultEventFilter | Module implementing Sentry.EventFilter |
:max_breadcrumbs | integer | 100 | Max breadcrumbs per process |
:max_stacktrace_arg_length | integer | 10000 | Max length (in graphemes) of each inspected function argument in stacktrace vars (v13.2.0+) |
:dedup_events | boolean | true | Deduplicate identical events within ~30 seconds |
:tags | map | %{} | Global tags sent with every event |
:traces_sample_rate | `float \ | nil` | nil |
:traces_sampler | `fn \ | {m, f} \ | nil` |
:enable_logs | boolean | false | Enable Sentry Logs Protocol (v12.0.0+) |
:scrubber | keyword | [] | Scrubber config (v13.1.1+); keys: :conn_private_allow_list (list of atoms kept from Plug.Conn.private) |
:test_mode | boolean | false | Capture events in-memory for testing |
Default PII Guidance
Most Sentry SDKs expose a send-default-PII option. As of sentry v12, the Elixir SDK does not expose a send_default_pii config option in its documented option list or current config schema, so do not add a non-existent option. For richer user context, use Sentry.PlugContext and explicitly set allowed fields with Sentry.Context.set_user_context/1, then scrub with :before_send if needed. If a future Elixir SDK release adds send_default_pii, recommend setting it.
Automatic PII Scrubbing: As of v13.1.0, stacktrace frame variables and FunctionClauseError/Phoenix.ActionClauseError arguments are automatically scrubbed for sensitive data using the same scrubber rules as HTTP request data. Use :scrubber config to customize which Plug.Conn.private keys are retained.
Environment Variables
| Variable | Maps to | Purpose |
|---|---|---|
SENTRY_DSN | :dsn | Data Source Name |
SENTRY_RELEASE | :release | App version (e.g., my-app@1.0.0) |
SENTRY_ENVIRONMENT | :environment_name | Deployment environment |
---
Verification
Test that Sentry is receiving events:
# Send a test event from your project
MIX_ENV=dev mix sentry.send_test_eventOr add a temporary call in a controller action:
# Temporary test — remove after confirming
def index(conn, _params) do
Sentry.capture_message("Sentry Elixir SDK test event")
text(conn, "sent")
endCheck the Sentry dashboard within a few seconds. If nothing appears: 1. Set config :sentry, log_level: :debug for verbose SDK output 2. Verify SENTRY_DSN is set and the project exists 3. Confirm :environment_name is not set to a value Sentry filters in your alert rules
---
Phase 4: Cross-Link
After completing Elixir setup, check for a companion frontend missing Sentry coverage:
ls assets/ frontend/ web/ client/ ui/ 2>/dev/null
cat assets/package.json frontend/package.json 2>/dev/null | grep -E '"react"|"svelte"|"vue"|"next"'If a frontend directory exists without Sentry configured, suggest the matching skill:
| Frontend detected | Suggest skill |
|---|---|
| React / Next.js | sentry-react-sdk or sentry-nextjs-sdk |
| Svelte / SvelteKit | sentry-svelte-sdk |
| Vue | See docs.sentry.io/platforms/javascript/guides/vue/ |
| Other JS/TS | sentry-browser-sdk |
Connecting Phoenix backend and JavaScript frontend with linked Sentry projects enables distributed tracing — stack traces that span the browser, Phoenix HTTP server, and downstream services in a single trace view.
---
Troubleshooting
| Issue | Solution |
|---|---|
| Events not appearing | Verify SENTRY_DSN is set; run mix sentry.send_test_event; set log_level: :debug |
| Missing stack traces on captured exceptions | Pass stacktrace: __STACKTRACE__ in the rescue block: Sentry.capture_exception(e, stacktrace: __STACKTRACE__) |
PlugCapture not working on Bandit | Sentry.PlugCapture is Cowboy-only; with Bandit errors surface via LoggerHandler |
| Source code context missing in production | Run mix sentry.package_source_code before building your OTP release |
| Context not appearing on async events | Sentry.Context.* is process-scoped; pass values explicitly or propagate Logger metadata across processes |
| Oban integration not reporting crons | Requires Oban v2.17.6+ or Oban Pro; cron jobs must have "cron" => true in job meta |
| Duplicate events from Cowboy/Bandit crashes | Set excluded_domains: [:cowboy, :bandit] in LoggerHandler config (both excluded by default as of v13.1.0) |
finch not starting | Ensure {:finch, "~> 0.21"} is in deps; Finch is the default HTTP client since v12.0.0 |
| JSON encoding error | Add {:jason, "~> 1.4"} and set json_library: Jason for Elixir < 1.18 |
Crons — Sentry Elixir SDK
Minimum SDK: sentry v10.2.0+Sentry Cron Monitoring detects when scheduled jobs fail silently — they don't error, but they stop running or take too long. The SDK provides three integration paths: manual check-ins (any scheduler), Oban (job queue), and Quantum (cron scheduler).
Manual Check-Ins
Use Sentry.capture_check_in/1 with any periodic task — GenServer, Task, or custom scheduler.
Basic pattern: start → work → complete/error
defmodule MyApp.ReportWorker do
use GenServer
def handle_info(:run, state) do
# 1. Signal job started
{:ok, check_in_id} = Sentry.capture_check_in(
status: :in_progress,
monitor_slug: "daily-report"
)
# 2. Do the work
result = MyApp.Reports.generate_daily_report()
# 3. Signal completion or failure
case result do
{:ok, _report} ->
Sentry.capture_check_in(
check_in_id: check_in_id,
status: :ok,
monitor_slug: "daily-report"
)
{:error, reason} ->
Sentry.capture_check_in(
check_in_id: check_in_id,
status: :error,
monitor_slug: "daily-report"
)
Logger.error("Report generation failed: #{inspect(reason)}")
end
{:noreply, state}
end
endWith monitor configuration (upsert)
Providing monitor_config creates or updates the monitor definition in Sentry on first check-in. This eliminates the need to create monitors in the Sentry UI manually:
Sentry.capture_check_in(
status: :in_progress,
monitor_slug: "hourly-sync",
monitor_config: [
schedule: [type: :crontab, value: "0 * * * *"], # runs every hour at :00
timezone: "America/New_York",
checkin_margin: 5, # minutes before Sentry considers the check-in missed
max_runtime: 30, # minutes before Sentry considers the job failed
failure_issue_threshold: 2,
recovery_threshold: 2,
owner: "platform-team" # since v10.10.0
]
)Interval schedule
For jobs that run every N minutes/hours rather than on a crontab:
Sentry.capture_check_in(
status: :in_progress,
monitor_slug: "health-probe",
monitor_config: [
schedule: [type: :interval, value: 15, unit: :minute],
# unit options: :year | :month | :week | :day | :hour | :minute
checkin_margin: 3,
max_runtime: 5
]
)capture_check_in/1 options
| Option | Type | Required | Description |
|---|---|---|---|
:status | `:in_progress \ | :ok \ | :error` |
:monitor_slug | string | Yes | Unique identifier for the monitor (slug format) |
:check_in_id | string | On completion | ID from the initial :in_progress call |
:duration | number | No | Job duration in seconds (auto-calculated when using check_in_id) |
:monitor_config | keyword | No | Monitor definition; upserted on each call |
:environment | string | No | Override default environment for this check-in |
capture_check_in/1 returns:
{:ok, check_in_id}— check-in ID string; pass it to subsequent calls:ignored— not sent (no DSN, wrong environment, etc.){:error, ClientError.t()}— HTTP error
Helper wrapper pattern
For clean code, wrap the check-in lifecycle in a helper:
defmodule MyApp.Crons do
@doc """
Runs a function as a Sentry-monitored cron job.
Returns {:ok, result} or {:error, exception}.
"""
def monitor(slug, fun, monitor_config \\ []) do
{:ok, check_in_id} = Sentry.capture_check_in(
status: :in_progress,
monitor_slug: slug,
monitor_config: monitor_config
)
try do
result = fun.()
Sentry.capture_check_in(
check_in_id: check_in_id,
status: :ok,
monitor_slug: slug
)
{:ok, result}
rescue
exception ->
Sentry.capture_check_in(
check_in_id: check_in_id,
status: :error,
monitor_slug: slug
)
Sentry.capture_exception(exception, stacktrace: __STACKTRACE__)
{:error, exception}
end
end
end
# Usage
MyApp.Crons.monitor("nightly-cleanup", fn ->
MyApp.Cleanup.run()
end, schedule: [type: :crontab, value: "0 3 * * *"])---
Oban Integration
Requires: Oban v2.17.6+ or Oban Pro v0.14+
Error capture (since v10.9.0)
Report failed Oban job errors to Sentry automatically:
# config/config.exs
config :sentry,
integrations: [
oban: [
capture_errors: true
]
]Errors from all Oban workers are captured with job context included.
Cron monitoring (since v10.2.0)
Monitor scheduled Oban jobs automatically. The integration reads cron metadata set by Oban Pro (or manually via job meta):
# config/config.exs
config :sentry,
integrations: [
oban: [
capture_errors: true,
cron: [
enabled: true
]
]
]Jobs are only monitored if their meta contains "cron" => true. Oban Pro sets this automatically. For standard Oban, add it manually:
# Scheduling a cron job with Oban (standard, not Pro)
Oban.insert(%Oban.Job{
worker: MyApp.DailyReportWorker,
meta: %{"cron" => true, "cron_expr" => "0 8 * * *"}
})Per-worker monitor configuration (since v10.9.0)
Override monitor settings per worker using the Sentry.Integrations.Oban.Cron callback:
defmodule MyApp.DailyReportWorker do
use Oban.Worker, queue: :reports
@behaviour Sentry.Integrations.Oban.Cron # optional callback
@impl Sentry.Integrations.Oban.Cron
def sentry_check_in_configuration(_job) do
[
monitor_config: [
timezone: "America/New_York",
checkin_margin: 10,
max_runtime: 60
]
]
end
@impl Oban.Worker
def perform(%Oban.Job{} = job) do
# ... job logic
:ok
end
endCustom error reporting filter (since v12.0.0)
Suppress reporting for specific noisy workers:
config :sentry,
integrations: [
oban: [
capture_errors: true,
should_report_error_callback: fn worker, _job ->
worker not in [MyApp.NoisyWorker, MyApp.ExpectedFailureWorker]
end
]
]Custom monitor slug generator
defmodule MyApp.ObanSlugger do
def generate_slug(%Oban.Job{worker: worker}) do
worker
|> Module.split()
|> Enum.map(&Macro.underscore/1)
|> Enum.join("-")
end
end
config :sentry,
integrations: [
oban: [
cron: [
enabled: true,
monitor_slug_generator: {MyApp.ObanSlugger, :generate_slug}
]
]
]---
Quantum Integration
Requires: Quantum v3.0+
Enable cron monitoring
# mix.exs
{:quantum, "~> 3.0"}# config/config.exs
config :sentry,
integrations: [
quantum: [
cron: [
enabled: true
]
]
]The Quantum integration automatically reads cron expressions from your Quantum scheduler configuration and creates monitors for each job. The monitor slug is derived from the job name.
# lib/my_app/scheduler.ex
defmodule MyApp.Scheduler do
use Quantum, otp_app: :my_app
end
# config/config.exs
config :my_app, MyApp.Scheduler,
jobs: [
{"0 * * * *", {MyApp.HourlyTask, :run, []}}, # monitored as "hourly_task"
{"@daily", {MyApp.DailyReport, :run, []}}, # monitored as "daily_report"
]Note: Quantum jobs using @reboot are not monitored (no equivalent schedule type in Sentry Crons).---
Monitor Configuration Reference
| Option | Type | Description |
|---|---|---|
schedule.type | `:crontab \ | :interval` |
schedule.value | string (crontab) or integer (interval) | Crontab expression or interval count |
schedule.unit | `:minute \ | :hour \ |
timezone | string | IANA timezone (e.g., "America/New_York") |
checkin_margin | integer | Minutes after expected start before marking missed |
max_runtime | integer | Minutes from start before marking timed out |
failure_issue_threshold | integer | Consecutive failures before opening an issue |
recovery_threshold | integer | Consecutive successes before closing the issue |
owner | string | Team or user slug (since v10.10.0) |
Best Practices
- Always call
Sentry.capture_check_in/1with:in_progressbefore starting work and:okor:erroron completion — sending only:okat the end still works but loses duration tracking - Wrap job logic in a try/rescue so failures also send the
:errorstatus (see helper wrapper pattern above) - Use
monitor_configon the first check-in of a new job to create the monitor automatically — no need to set it on every subsequent check-in - Set
checkin_marginto a reasonable buffer (e.g., 5 minutes for hourly jobs) to avoid false alarms from minor scheduling jitter - For Oban, prefer the built-in integration over manual check-ins — it handles the check-in lifecycle and job context enrichment automatically
Troubleshooting
| Issue | Solution |
|---|---|
| Monitor not appearing in Sentry | Send at least one :in_progress check-in with monitor_config to create the monitor |
| Oban integration not monitoring crons | Requires Oban v2.17.6+ or Oban Pro; job meta must contain "cron" => true |
capture_check_in/1 returns :ignored | DSN is not set or :environment_name is excluded in your Sentry alert filters |
Quantum @reboot jobs not monitored | Expected — @reboot has no crontab/interval equivalent; use manual check-ins for one-time startup jobs |
| Missed check-ins on deploy | If the app restarts during a cron window, the check-in is missed; increase checkin_margin to account for deploy time |
Error Monitoring — Sentry Elixir SDK
Minimum SDK: sentry v8.0.0+Configuration
Key config options for error monitoring:
| Option | Type | Default | Purpose |
|---|---|---|---|
:dsn | `string \ | nil` | nil |
:sample_rate | float | 1.0 | Error event sample rate (0.0–1.0) |
:before_send | `(event -> event \ | nil \ | false) \ |
:after_send_event | `(event, result -> any) \ | {m, f}` | nil |
:filter | module | Sentry.DefaultEventFilter | Module implementing Sentry.EventFilter |
:max_breadcrumbs | integer | 100 | Max breadcrumbs stored per process |
:dedup_events | boolean | true | Deduplicate identical events within ~30 seconds |
:tags | map | %{} | Global tags sent with every event |
:enable_source_code_context | boolean | false | Include source lines around errors |
:root_source_code_paths | [path] | [] | Required when source context is enabled |
:in_app_otp_apps | [atom] | [] | OTP apps whose modules appear as "in-app" in stacktraces |
Code Examples
Basic setup
# config/config.exs
config :sentry,
dsn: System.get_env("SENTRY_DSN"),
environment_name: config_env(),
enable_source_code_context: true,
root_source_code_paths: [File.cwd!()],
in_app_otp_apps: [:my_app]Capturing exceptions
Always pass stacktrace: __STACKTRACE__ in rescue blocks — Elixir only populates __STACKTRACE__ inside a rescue or catch clause:
try do
perform_risky_operation()
rescue
exception ->
Sentry.capture_exception(exception, stacktrace: __STACKTRACE__)
reraise exception, __STACKTRACE__
endWith extra context:
try do
process_order(order_id)
rescue
exception ->
Sentry.capture_exception(exception,
stacktrace: __STACKTRACE__,
extra: %{order_id: order_id},
tags: %{region: "us-east-1"},
level: :error
)
endCapturing messages
# Simple message
Sentry.capture_message("Payment gateway timeout")
# With context
Sentry.capture_message("Queue depth exceeded threshold",
extra: %{depth: 5000, limit: 1000},
tags: %{queue: "payments"},
level: :warning
)
# With interpolation (since v10.1.0)
Sentry.capture_message("Failed to process user %s after %d attempts",
interpolation_parameters: [user_id, attempt_count]
)Context enrichment with Sentry.Context
Context is stored per-process (in Logger metadata). Set it early in request handling — in a Plug, LiveView mount, or GenServer handler:
# Set user identity
Sentry.Context.set_user_context(%{
id: current_user.id,
username: current_user.username,
email: current_user.email,
ip_address: "{{auto}}" # Sentry infers from request headers
})
# Set tags (searchable in Sentry)
Sentry.Context.set_tags_context(%{
subscription_tier: "pro",
region: "us-east-1"
})
# Set extra context (not searchable — use tags for filtering)
Sentry.Context.set_extra_context(%{
order_id: "abc-123",
items_count: 5
})
# Set request context (URL, method, headers)
Sentry.Context.set_request_context(%{
url: conn.request_path,
method: conn.method,
headers: Enum.into(conn.req_headers, %{})
})
# Add a breadcrumb
Sentry.Context.add_breadcrumb(%{
category: "auth",
message: "User authenticated",
level: :info,
data: %{method: "oauth2", provider: "github"}
})Important:Sentry.Contextdata is scoped to the current process only. It is NOT automatically propagated to spawnedTaskorGenServerprocesses. For async work, pass context values explicitly.
Context in a Phoenix controller (via Plug)
defmodule MyAppWeb.Plugs.SentryContext do
@behaviour Plug
def init(opts), do: opts
def call(conn, _opts) do
if user = conn.assigns[:current_user] do
Sentry.Context.set_user_context(%{
id: user.id,
username: user.username,
email: user.email
})
end
Sentry.Context.set_request_context(%{
url: Phoenix.Controller.current_url(conn),
method: conn.method,
headers: Enum.into(conn.req_headers, %{})
})
conn
end
end
# In your router pipeline:
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :put_secure_browser_headers
plug MyAppWeb.Plugs.SentryContext
endBreadcrumbs
Sentry.Context.add_breadcrumb(%{
type: "http",
category: "http",
message: "GET https://api.stripe.com/v1/charges",
level: :info,
data: %{
url: "https://api.stripe.com/v1/charges",
method: "GET",
status_code: 200
}
})
Sentry.Context.add_breadcrumb(%{
category: "db.query",
message: "SELECT * FROM orders WHERE id = ?",
level: :debug,
data: %{duration_ms: 42}
})Before-send hook
Use :before_send to mutate or drop events before they are sent:
defmodule MyApp.SentryHooks do
def before_send(event) do
# Drop events from test/health endpoints
if get_in(event, [:request, :url]) |> String.contains?("/health") do
nil # return nil or false to drop the event
else
# Scrub PII from request headers
event = put_in(event, [:request, :headers, "authorization"], "[FILTERED]")
# Enrich with deployment metadata
put_in(event, [:extra, :deploy_sha], System.get_env("GIT_SHA"))
end
end
end
# config/config.exs
config :sentry,
before_send: {MyApp.SentryHooks, :before_send}Custom event filter
Sentry.EventFilter is called before before_send and before sampling. Returning true from exclude_exception?/2 silently drops the event:
defmodule MyApp.SentryFilter do
@behaviour Sentry.EventFilter
@impl Sentry.EventFilter
def exclude_exception?(%MyApp.NotFoundError{}, _source), do: true
def exclude_exception?(%MyApp.ValidationError{}, _source), do: true
def exclude_exception?(exception, source) do
# Delegate other exceptions to the default filter
Sentry.DefaultEventFilter.exclude_exception?(exception, source)
end
end
# config/config.exs
config :sentry, filter: MyApp.SentryFilterSentry.DefaultEventFilter already excludes common Phoenix/Plug noise:
Ecto.NoResultsErrorPhoenix.Router.NoRouteErrorPlug.Parsers.BadEncodingError,ParseError,RequestTooLargeError,UnsupportedMediaTypeError
Fingerprinting and custom grouping
Override Sentry's default grouping algorithm via before_send:
def before_send(%{exception: [%{type: "MyApp.DatabaseError"} | _]} = event) do
%{event | fingerprint: ["database-connection", event.extra[:db_host]]}
end
def before_send(event) do
# Extend default grouping with additional discriminators
if event.exception != [] do
%{event | fingerprint: ["{{ default }}", System.get_env("RELEASE_NODE")]}
else
event
end
endAttachments (since v10.1.0)
Sentry.Context.add_attachment(%Sentry.Attachment{
filename: "debug.log",
data: File.read!("debug.log")
})
# Then capture the exception as usual
Sentry.capture_exception(exception, stacktrace: __STACKTRACE__)Flush pending events
# Default 5-second timeout
Sentry.flush()
# Custom timeout
Sentry.flush(timeout: 10_000)Source Code Context in Production
Without packaging, production releases strip source code — Sentry cannot show the lines around an error. Package your source before building:
# Run before mix release
mix sentry.package_source_codeOTP 28 compatibility — use string patterns instead of compiled regexps:
# config/config.exs
config :sentry,
source_code_exclude_patterns: ["/_build/", "/deps/", "/priv/", "/test/"]send_result Types
| Value | Description |
|---|---|
{:ok, event_id} | Event sent successfully (:send_result: :sync only) |
:ignored | Not sent (no DSN, filtered, sampled out) |
:excluded | Dropped by EventFilter |
{:error, ClientError.t()} | HTTP-level send error |
Best Practices
- Always pass
stacktrace: __STACKTRACE__in rescue blocks — stacktraces are not automatically captured in Elixir - Set
in_app_otp_apps: [:my_app]to distinguish your code from library code in Sentry's issue grouping - Use
Sentry.Context.set_user_context/1early in the request lifecycle (e.g., in a Plug) so every event from that process includes user identity - Use
Sentry.EventFilterfor structural filtering (known non-errors), andbefore_sendfor event mutation or conditional dropping - Run
mix sentry.package_source_codeas part of your release build process so production stacktraces show source lines
Troubleshooting
| Issue | Solution |
|---|---|
| No stack trace on captured exception | Add stacktrace: __STACKTRACE__ to capture_exception/2 inside the rescue block |
| Events not appearing | Set log_level: :debug; check DSN; call Sentry.flush/1 before process exit |
| All events showing "in-app: false" | Set in_app_otp_apps: [:my_app] in config to mark your app's modules as in-app |
| Context missing from async events | Sentry.Context is process-scoped — pass data explicitly to spawned tasks/GenServers |
before_send not dropping events | Ensure function returns nil or false (not an empty map) to drop the event |
| Duplicate events (Cowboy + LoggerHandler) | Set excluded_domains: [:cowboy] in LoggerHandler config (default behavior) |
Logging — Sentry Elixir SDK
Minimum SDK:sentryv9.0.0+ forSentry.LoggerHandler; v12.0.0+ for Sentry Logs Protocol
The Elixir SDK provides two independent logging mechanisms:
1. `Sentry.LoggerHandler` — Erlang :logger handler that forwards crash reports and error log messages from your app to Sentry as error events. This is the primary way to catch errors that weren't explicitly passed to capture_exception/2.
2. Sentry Logs Protocol (v12.0.0+) — Forwards structured log entries to Sentry's Logs product, where they appear alongside errors and traces.
---
Sentry.LoggerHandler
Configuration
The recommended setup uses the :logger key in your app's config and activates handlers in Application.start/2.
Step 1: Define the handler in config
# config/config.exs
config :my_app, :logger, [
{:handler, :sentry_handler, Sentry.LoggerHandler, %{
config: %{
metadata: [:request_id, :user_id], # Logger metadata keys to include as extra context
capture_log_messages: true, # Send all :error messages, not just crash reports
level: :error # Minimum log level (default: :error)
}
}}
]Step 2: Activate in Application.start/2
# lib/my_app/application.ex
def start(_type, _args) do
Logger.add_handlers(:my_app) # activates all handlers defined in config :my_app, :logger
children = [
MyAppWeb.Endpoint
# ... other children
]
Supervisor.start_link(children, strategy: :one_for_one)
endAlternative: Add handler directly in Application.start/2
def start(_type, _args) do
:logger.add_handler(:sentry_handler, Sentry.LoggerHandler, %{
config: %{
metadata: [:request_id],
capture_log_messages: true,
level: :error
}
})
Supervisor.start_link(children, strategy: :one_for_one)
endLoggerHandler Configuration Options
| Option | Type | Default | Description |
|---|---|---|---|
:level | `Logger.level \ | nil` | :error |
:excluded_domains | [atom] | [:cowboy] | Domains to skip (cowboy excluded by default to avoid double-reporting with PlugCapture) |
:metadata | `[atom] \ | :all` | [] |
:tags_from_metadata | [atom] | [] | Metadata keys to promote to Sentry tags (searchable). Since v10.9.0 |
:capture_log_messages | boolean | false | When true, all :error+ log messages are sent; when false, only crash reports (supervisor crashes, process exits) are sent |
:rate_limiting | `[max_events: integer, interval: integer] \ | nil` | nil |
:sync_threshold | `non_neg_integer \ | nil` | 100 |
:discard_threshold | `non_neg_integer \ | nil` | nil |
Capturing specific log levels only
config :my_app, :logger, [
{:handler, :sentry_handler, Sentry.LoggerHandler, %{
config: %{
level: :warning, # :debug | :info | :warning | :error | :critical
capture_log_messages: true,
metadata: :all # include all Logger metadata
}
}}
]Rate limiting
Prevent log storms from flooding Sentry:
config :my_app, :logger, [
{:handler, :sentry_handler, Sentry.LoggerHandler, %{
config: %{
capture_log_messages: true,
level: :error,
rate_limiting: [max_events: 20, interval: 60_000] # max 20 events per minute
}
}}
]Promoting metadata to Sentry tags
Tags are indexed and searchable in Sentry. Promote high-value metadata keys:
config :my_app, :logger, [
{:handler, :sentry_handler, Sentry.LoggerHandler, %{
config: %{
metadata: [:request_id, :user_id, :region],
tags_from_metadata: [:region], # "region" becomes a searchable Sentry tag
capture_log_messages: true,
level: :error
}
}}
]LoggerBackend (legacy)
Sentry.LoggerBackend is the older Elixir Logger backend. Prefer LoggerHandler for new projects. LoggerBackend will eventually be deprecated.
# lib/my_app/application.ex
def start(_type, _args) do
Logger.add_backend(Sentry.LoggerBackend)
# ...
end
# config/config.exs
config :logger, Sentry.LoggerBackend,
level: :warning,
excluded_domains: [],
metadata: [:foo_bar],
capture_log_messages: true---
Sentry Logs Protocol (since v12.0.0)
The Sentry Logs feature sends structured log entries to Sentry's Logs product — separate from error events. This enables log search, log-to-trace correlation, and dashboards alongside your error data.
Enable
# config/config.exs
config :sentry,
enable_logs: true, # auto-attaches a TelemetryProcessor-backed LoggerHandler
logs: [
level: :info, # minimum log level (default: :info)
metadata: [:request_id, :user_id], # metadata keys to include as log attributes
excluded_domains: [:cowboy, :ecto_sql] # domains to skip
]enable_logs: true automatically wires up a Logger handler that captures log entries and forwards them to the Sentry Logs Protocol endpoint via the TelemetryProcessor.
Filter logs before sending
config :sentry,
enable_logs: true,
before_send_log: fn log_event ->
# Return nil to drop the log; return log_event to send it
if log_event.level == :debug, do: nil, else: log_event
endRoute all categories through TelemetryProcessor
By default only logs use the TelemetryProcessor ring buffer. You can route errors, check-ins, and transactions through it too:
config :sentry,
enable_logs: true,
telemetry_processor_categories: [:log, :error, :check_in, :transaction]---
How the Two Systems Interact
| What | LoggerHandler | Sentry Logs Protocol |
|---|---|---|
| Appears in Sentry | Issues (errors) | Logs product |
| Use for | Crash reports, unhandled errors | Structured log search, log-to-trace correlation |
| Min SDK version | v9.0.0 | v12.0.0 |
| Config key | :logger in app config | :enable_logs in sentry config |
You can run both simultaneously. A common setup: LoggerHandler at :error level for issues, and Sentry Logs at :info for structured log search.
---
Best Practices
- Prefer
Sentry.LoggerHandleroverSentry.LoggerBackendfor new projects —LoggerHandleris the Erlang:loggerhandler and runs in the calling process, which is more efficient - Set
excluded_domains: [:cowboy](the default) to avoid duplicate events when usingSentry.PlugCapturewith Cowboy - Enable
capture_log_messages: trueto catch error-level log messages that are not explicitcapture_exceptioncalls - Use
tags_from_metadatato promote high-cardinality identifiers (user ID, region, request ID) to searchable Sentry tags - Apply
rate_limitingin high-throughput services to prevent log storms from overwhelming your Sentry quota
Troubleshooting
| Issue | Solution |
|---|---|
| LoggerHandler not capturing anything | Verify Logger.add_handlers(:my_app) is called in Application.start/2 |
| Duplicate events from Cowboy crashes | excluded_domains: [:cowboy] is the default; check if it was removed from config |
| No Sentry Logs entries appearing | Ensure enable_logs: true is set and sentry v12.0.0+ is in use |
| Log metadata not appearing in Sentry | List keys explicitly in metadata: option; or use metadata: :all |
| Too many log events hitting quota | Add rate_limiting: [max_events: N, interval: ms] to LoggerHandler config |
LoggerBackend warnings in logs | Migrate to Sentry.LoggerHandler; LoggerBackend will be deprecated |
Tracing — Sentry Elixir SDK
Minimum SDK: sentry v11.0.0+ (beta); v12.0.0+ for distributed tracing and LiveView spansTracing in the Elixir SDK is implemented via OpenTelemetry. Sentry ships three OTel components: a SpanProcessor, a Sampler, and a Propagator. These integrate with the OpenTelemetry Elixir ecosystem so you can use any OTel-compatible instrumentation library (Phoenix, Ecto, Finch, etc.) and have all spans forwarded to Sentry.
Configuration
Dependencies
# mix.exs
defp deps do
[
{:sentry, "~> 12.0"},
{:finch, "~> 0.21"},
# OpenTelemetry core
{:opentelemetry, "~> 1.5"},
{:opentelemetry_api, "~> 1.4"},
{:opentelemetry_exporter, "~> 1.0"},
{:opentelemetry_semantic_conventions, "~> 1.27"},
# Optional: Phoenix and Ecto auto-instrumentation
{:opentelemetry_phoenix, "~> 2.0"},
{:opentelemetry_ecto, "~> 1.2"}
]
endSentry config
Any non-nil value for :traces_sample_rate enables tracing. Start with 1.0 for development, lower for production:
# config/config.exs
config :sentry,
dsn: System.get_env("SENTRY_DSN"),
traces_sample_rate: 1.0 # lower to 0.1 in high-traffic productionOpenTelemetry config
Wire Sentry's SpanProcessor and Sampler into the OTel pipeline:
# config/config.exs
config :opentelemetry,
span_processor: {Sentry.OpenTelemetry.SpanProcessor, []},
sampler: {Sentry.OpenTelemetry.Sampler, []}Distributed tracing (since v12.0.0)
Enable Sentry's propagator to inject and extract sentry-trace and baggage headers:
# config/config.exs
config :opentelemetry,
span_processor: {Sentry.OpenTelemetry.SpanProcessor, []},
sampler: {Sentry.OpenTelemetry.Sampler, []},
text_map_propagators: [
:trace_context,
:baggage,
Sentry.OpenTelemetry.Propagator
]Note: AddSentry.OpenTelemetry.Propagatorafter the standard:trace_contextand:baggagepropagators. It reads and writes the Sentry-specificsentry-traceandbaggageheaders so spans from Elixir connect to browser and backend spans from other Sentry SDKs.
Sampling
Uniform sample rate
config :sentry,
traces_sample_rate: 0.1 # 10% of all root spansCustom sampler function
Use :traces_sampler to apply per-operation logic. Overrides :traces_sample_rate when set:
config :sentry,
traces_sampler: fn sampling_context ->
case sampling_context.transaction_context.op do
"http.server" -> 0.1 # 10% of HTTP requests
"db.query" -> 0.01 # 1% of DB queries
_ -> false # drop everything else
end
endDrop specific transaction names
Use the built-in drop option of Sentry.OpenTelemetry.Sampler:
config :opentelemetry,
sampler: {Sentry.OpenTelemetry.Sampler, [drop: ["health_check", "liveness_check"]]}Phoenix Auto-Instrumentation
opentelemetry_phoenix automatically creates spans for each Phoenix request. Setup in Application.start/2:
# lib/my_app/application.ex
def start(_type, _args) do
Logger.add_handlers(:my_app)
OpentelemetryPhoenix.setup() # instruments Phoenix controllers and LiveView (requires opentelemetry_phoenix)
OpentelemetryEcto.setup([:my_app, :repo]) # instruments Ecto queries (requires opentelemetry_ecto)
children = [
MyApp.Repo,
MyAppWeb.Endpoint
]
Supervisor.start_link(children, strategy: :one_for_one)
endHow Spans Map to Sentry
| OTel span type | Sentry object |
|---|---|
| Root span (no local parent) | Transaction |
| Child span (has local parent) | Span within that transaction |
| Distributed span (remote parent, HTTP server or LiveView) | New Transaction root (linked via trace ID) |
Root spans are created when:
- An HTTP request arrives with no
sentry-traceparent (or sampling says yes) - A LiveView mounts (since v12.0.0)
- You manually start a root-level OTel span
Custom Spans
Use the standard OpenTelemetry API for custom instrumentation:
require OpenTelemetry.Tracer, as: Tracer
def process_order(order_id) do
Tracer.with_span "process_order", %{attributes: [{"order.id", order_id}]} do
# All work done inside this block is a child span
validate_order(order_id)
charge_payment(order_id)
send_confirmation(order_id)
end
end
def validate_order(order_id) do
Tracer.with_span "validate_order", %{kind: :internal} do
# Nested child span
# ...
end
endSetting span attributes
Tracer.with_span "db.query" do
Tracer.set_attributes([
{"db.system", "postgresql"},
{"db.statement", "SELECT * FROM orders WHERE id = $1"},
{"db.rows_affected", 1}
])
# run query
endPropagating context through async code
OTel context must be explicitly propagated when crossing process boundaries:
# Capture current context before spawning
ctx = OpenTelemetry.Ctx.get_current()
Task.start(fn ->
# Attach parent context in the new process
OpenTelemetry.Ctx.attach(ctx)
Tracer.with_span "async.work" do
perform_work()
end
end)OpenTelemetry Components Reference
| Module | OTel behaviour | Purpose |
|---|---|---|
Sentry.OpenTelemetry.SpanProcessor | :otel_span_processor | Converts finished OTel spans into Sentry transactions/spans |
Sentry.OpenTelemetry.Sampler | :otel_sampler | Applies traces_sample_rate / traces_sampler to root spans |
Sentry.OpenTelemetry.Propagator | :otel_propagator_text_map | Injects/extracts sentry-trace and baggage headers |
Best Practices
- Set
traces_sample_rate: 1.0in development and0.1–0.2in production; adjust per route withtraces_sampler - Use the
drop:option inSentry.OpenTelemetry.Samplerto exclude health check endpoints from tracing - Always call
OpentelemetryPhoenix.setup()andOpentelemetryEcto.setup/1inApplication.start/2before the supervision tree starts - Propagate OTel context explicitly when spawning tasks or sending messages to other processes
- Add
Sentry.OpenTelemetry.Propagatorfor distributed tracing across services — without it, backend traces won't link to browser Sentry events
Troubleshooting
| Issue | Solution |
|---|---|
| No transactions in Sentry | Verify traces_sample_rate is set (non-nil); confirm span_processor is configured in :opentelemetry config |
| Phoenix spans missing | Call OpentelemetryPhoenix.setup() in Application.start/2 before the supervision tree |
| Ecto query spans missing | Call OpentelemetryEcto.setup([:my_app, :repo]) in Application.start/2 |
| Distributed trace not linking | Add Sentry.OpenTelemetry.Propagator to text_map_propagators; requires v12.0.0+ |
| LiveView spans not appearing | Requires v12.0.0+ and opentelemetry_phoenix ~> 2.0 |
Context lost in async Task | Capture OpenTelemetry.Ctx.get_current() before spawning; call OpenTelemetry.Ctx.attach(ctx) inside the task |
| Too many DB spans | Use traces_sampler to lower sample rate for "db.query" operations |
Related skills
How it compares
Pick sentry-elixir-sdk over generic Sentry error setup when scheduled Elixir jobs fail silently without exceptions.
FAQ
Do I need the Igniter installer or can I set up Sentry manually?
Igniter (sentry v11.0.0+) is recommended — it auto-configures config/ and Application.start/2 interactively. If you prefer manual setup, follow the 5-step guide: add to mix.exs, configure DSN/env, activate LoggerHandler in application.ex, add PlugCapture/PlugContext to endpoint,
What is LoggerHandler and when is it activated?
LoggerHandler is Sentry.LoggerHandler configured in config/config.exs and activated with Logger.add_handlers(:my_app) in Application.start/2. It forwards crash reports and error-level logs to Sentry, capturing exceptions that aren't explicit Sentry.capture_exception/2 calls.
How do I enable tracing and what are the prerequisites?
Set :traces_sample_rate to a float > 0.0 in config.exs, ensure OpenTelemetry is detected in mix.exs, and load references/tracing.md for Ecto/HTTP adapter setup. Tracing connects HTTP requests to database queries and downstream services in a single trace view.
Is Sentry Elixir Sdk safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.