sentry-elixir-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAll Skills > SDK Setup > Elixir SDK
所有技能 > SDK设置 > Elixir SDK
Sentry Elixir SDK
Sentry Elixir SDK
Opinionated wizard that scans your Elixir project and guides you through complete Sentry setup.
这是一个智能向导,会扫描你的Elixir项目并引导你完成Sentry的完整设置。
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 hex package,
sentry, or Elixir Sentry SDKgetsentry/sentry-elixir - 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 v12.0.2, requires Elixir ~> 1.13). Always verify against docs.sentry.io/platforms/elixir/ before implementing.
- 用户要求在Elixir或Phoenix应用中"添加Sentry"或"设置Sentry"
- 用户需要为Elixir或Phoenix应用配置错误监控、链路追踪、日志记录或定时任务监控
- 用户提到hex包、
sentry或Elixir Sentry SDKgetsentry/sentry-elixir - 用户希望监控异常、Plug错误、LiveView错误或定时任务
注意: 以下的SDK版本和API内容基于编写时的Sentry文档(sentry v12.0.2,要求Elixir ~> 1.13)。 在实施前,请务必对照docs.sentry.io/platforms/elixir/进行验证。
Phase 1: Detect
阶段1:项目检测
Run these commands to understand the project before making any recommendations:
bash
undefined在给出任何建议前,运行以下命令来了解项目情况:
bash
undefinedCheck existing Sentry dependency
Check existing Sentry dependency
grep -i sentry mix.exs 2>/dev/null
grep -i sentry mix.exs 2>/dev/null
Detect Elixir version
Detect Elixir version
cat .tool-versions 2>/dev/null | grep elixir
grep "elixir:" mix.exs 2>/dev/null
cat .tool-versions 2>/dev/null | grep elixir
grep "elixir:" mix.exs 2>/dev/null
Detect Phoenix or Plug
Detect Phoenix or Plug
grep -E '"phoenix"|"plug"' mix.exs 2>/dev/null
grep -E '"phoenix"|"plug"' mix.exs 2>/dev/null
Detect Phoenix LiveView
Detect Phoenix LiveView
grep "phoenix_live_view" mix.exs 2>/dev/null
grep "phoenix_live_view" mix.exs 2>/dev/null
Detect Oban (job queue / crons)
Detect Oban (job queue / crons)
grep "oban" mix.exs 2>/dev/null
grep "oban" mix.exs 2>/dev/null
Detect Quantum (cron scheduler)
Detect Quantum (cron scheduler)
grep "quantum" mix.exs 2>/dev/null
grep "quantum" mix.exs 2>/dev/null
Detect OpenTelemetry usage
Detect OpenTelemetry usage
grep "opentelemetry" mix.exs 2>/dev/null
grep "opentelemetry" mix.exs 2>/dev/null
Check for companion frontend
Check for companion frontend
ls assets/ frontend/ web/ client/ 2>/dev/null
**What 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 |
---ls assets/ frontend/ web/ client/ 2>/dev/null
**需要关注的信息:**
| 信号 | 影响 |
|--------|--------|
| `mix.exs`中已存在`sentry`? | 跳过安装步骤,直接进入阶段2(功能配置) |
| 检测到Phoenix? | 添加`Sentry.PlugCapture`、`Sentry.PlugContext`,可选添加`Sentry.LiveViewHook` |
| 检测到LiveView? | 在`my_app_web.ex`的`live_view`宏中添加`Sentry.LiveViewHook` |
| 检测到Oban? | 推荐通过Oban集成实现定时任务监控和错误捕获 |
| 检测到Quantum? | 推荐通过Quantum集成实现定时任务监控 |
| 检测到已使用OpenTelemetry? | 链路追踪仅需配置`Sentry.OpenTelemetry.*` |
| 发现前端目录? | 触发阶段4的跨端配置建议 |
---Phase 2: Recommend
阶段2:配置建议
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 — forwards crash reports and error logs to Sentry
Sentry.LoggerHandler - ✅ 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 — |
| Tracing | Phoenix, Plug, Ecto, or OpenTelemetry imports detected |
| Crons | Oban, Quantum, or periodic |
| 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?"
根据检测结果,给出具体的配置建议。不要提出开放式问题,直接给出方案:
推荐(核心覆盖):
- ✅ 错误监控 — 必选;捕获异常和崩溃报告
- ✅ 日志记录 — 会将崩溃报告和错误日志转发至Sentry
Sentry.LoggerHandler - ✅ 链路追踪 — 若检测到Phoenix、Plug或Ecto(通过OpenTelemetry实现)
可选(增强可观测性):
- ⚡ 定时任务监控 — 检测定时任务的静默失败(Oban、Quantum或手动实现的GenServer)
- ⚡ Sentry日志转发 — 将结构化日志转发至Sentry日志协议(需sentry v12.0.0+)
建议逻辑:
| 功能 | 推荐场景 |
|---|---|
| 错误监控 | 始终推荐 — 不可或缺的基础功能 |
| 日志记录 | 始终推荐 — |
| 链路追踪 | 检测到Phoenix、Plug、Ecto或OpenTelemetry引入时 |
| 定时任务监控 | 检测到Oban、Quantum或周期性 |
| Sentry日志转发 | 使用sentry v12.0.0+且需要结构化日志搜索时 |
建议话术:"我建议设置错误监控+日志记录[+若检测到Phoenix/Ecto则添加链路追踪]。是否需要同时添加定时任务监控或Sentry日志转发功能?"
Phase 3: Guide
阶段3:分步引导
Option 1: Igniter Installer (Recommended)
选项1:使用Igniter安装器(推荐)
You need to run this yourself — the Igniter installer requires interactive terminal input that the agent can't handle. Copy-paste into your terminal:bashmix igniter.install sentryAvailable since sentry v11.0.0. It auto-configures,config/config.exs,config/prod.exs, andconfig/runtime.exs.lib/my_app/application.exOnce it finishes, come back and skip to Verification.
If the user skips the Igniter installer, proceed with Option 2 (Manual Setup) below.
你需要自行运行此命令 — Igniter安装器需要交互式终端输入,无法由代理完成。复制以下命令到终端运行:bashmix igniter.install sentry此功能从sentry v11.0.0开始提供。它会自动配置、config/config.exs、config/prod.exs和config/runtime.exs。lib/my_app/application.ex安装完成后,返回并跳至验证步骤。
如果用户选择跳过Igniter安装器,请继续以下选项2(手动设置)。
Option 2: Manual Setup
选项2:手动设置
Install
安装依赖
Add to dependencies:
mix.exselixir
undefined在的依赖中添加:
mix.exselixir
undefinedmix.exs
mix.exs
defp deps do
[
{:sentry, "> 12.0"},
{:finch, "> 0.21"}
# Add jason if using Elixir < 1.18:
# {:jason, "~> 1.4"},
]
end
```bash
mix deps.getdefp deps do
[
{:sentry, "> 12.0"},
{:finch, "> 0.21"}
# Add jason if using Elixir < 1.18:
# {:jason, "~> 1.4"},
]
end
```bash
mix deps.getConfigure
基础配置
elixir
undefinedelixir
undefinedconfig/config.exs
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):
```elixirconfig :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]
对于运行时配置(推荐用于DSN和版本号配置):
```elixirconfig/runtime.exs
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)}")
undefinedimport Config
config :sentry,
dsn: System.fetch_env!("SENTRY_DSN"),
release: System.get_env("SENTRY_RELEASE", "my-app@#{Application.spec(:my_app, :vsn)}")
undefinedQuick Start — Recommended Init Config
快速开始 — 推荐初始化配置
This config enables the most features with sensible defaults:
elixir
undefined以下配置可启用最多功能并使用合理默认值:
elixir
undefinedconfig/config.exs
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
}
}}
]
undefinedconfig :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
}
}}
]
undefinedActivate Logger Handler
启用日志处理器
Add in :
Logger.add_handlers/1Application.start/2elixir
undefined在中添加:
Application.start/2Logger.add_handlers/1elixir
undefinedlib/my_app/application.ex
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)
end
undefineddef 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)
end
undefinedPhoenix Integration
Phoenix集成
lib/my_app_web/endpoint.exelixir
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:is only needed for the Cowboy adapter. Phoenix 1.7+ defaults to Bandit, whereSentry.PlugCaptureis harmless but unnecessary.PlugCaptureis always recommended — it enriches events with HTTP request data.Sentry.PlugContext
LiveView errors —
lib/my_app_web.exelixir
def live_view do
quote do
use Phoenix.LiveView
on_mount Sentry.LiveViewHook # captures errors in mount/handle_event/handle_info
end
endlib/my_app_web/endpoint.exelixir
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
# ...
end注意:仅适用于Cowboy适配器。Phoenix 1.7+默认使用Bandit适配器,此时Sentry.PlugCapture无害但非必需。PlugCapture始终推荐使用——它会为事件补充HTTP请求数据。Sentry.PlugContext
LiveView错误监控 —
lib/my_app_web.exelixir
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
纯Plug应用
elixir
defmodule MyApp.Router do
use Plug.Router
use Sentry.PlugCapture # Cowboy only
plug Plug.Parsers, parsers: [:urlencoded, :multipart]
plug Sentry.PlugContext
# ...
endelixir
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 | | Always (baseline) |
| Tracing | | Phoenix / Ecto / OpenTelemetry detected |
| Logging | | |
| Crons | | Oban, Quantum, or periodic jobs detected |
For each feature: , follow steps exactly, verify it works.
Read ${SKILL_ROOT}/references/<feature>.md逐个功能进行配置。加载每个功能对应的参考文件,按照步骤操作,并在进入下一个功能前验证配置生效:
| 功能 | 参考文件 | 加载时机 |
|---|---|---|
| 错误监控 | | 始终加载(基础功能) |
| 链路追踪 | | 检测到Phoenix / Ecto / OpenTelemetry时 |
| 日志记录 | | 配置 |
| 定时任务监控 | | 检测到Oban、Quantum或周期性任务时 |
对于每个功能:读取,严格按照步骤操作,验证功能正常运行。
${SKILL_ROOT}/references/<feature>.mdConfiguration Reference
配置参考
Key Config Options
关键配置选项
| Option | Type | Default | Purpose |
|---|---|---|---|
| | | SDK disabled if nil; env: |
| | | e.g., |
| | | e.g., |
| | | Error event sample rate (0.0–1.0) |
| | | Include source lines around errors |
| | | Required when source context is enabled |
| | | OTP apps whose modules are "in-app" in stacktraces |
| | | Hook to mutate or drop error events |
| | | Hook called after event is sent |
| | | Module implementing |
| | | Max breadcrumbs per process |
| | | Deduplicate identical events within ~30 seconds |
| | | Global tags sent with every event |
| | | Non-nil enables tracing (requires OTel setup) |
| | | Custom per-transaction sampling |
| | | Enable Sentry Logs Protocol (v12.0.0+) |
| | | Capture events in-memory for testing |
| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | | 若为nil则SDK禁用;可通过环境变量 |
| | | 例如 |
| | | 例如 |
| | | 错误事件采样率(0.0–1.0) |
| | | 在错误信息中包含源代码上下文 |
| | | 启用源代码上下文时必填 |
| | | 栈追踪中标记为“应用内”的OTP应用模块 |
| | | 用于修改或丢弃错误事件的钩子 |
| | | 事件发送后调用的钩子 |
| | | 实现 |
| | | 每个进程的最大面包屑(事件上下文)数量 |
| | | 在约30秒内去重相同事件 |
| | | 随每个事件发送的全局标签 |
| | | 非nil时启用链路追踪(需配置OTel) |
| | | 自定义事务采样逻辑 |
| | | 启用Sentry日志协议(v12.0.0+) |
| | | 测试模式下将事件捕获到内存中 |
Environment Variables
环境变量
| Variable | Maps to | Purpose |
|---|---|---|
| | Data Source Name |
| | App version (e.g., |
| | Deployment environment |
| 变量 | 对应配置项 | 用途 |
|---|---|---|
| | 数据源名称 |
| | 应用版本(例如 |
| | 部署环境 |
Verification
验证
Test that Sentry is receiving events:
bash
undefined测试Sentry是否能接收事件:
bash
undefinedSend a test event from your project
Send a test event from your project
MIX_ENV=dev mix sentry.send_test_event
Or add a temporary call in a controller action:
```elixirMIX_ENV=dev mix sentry.send_test_event
或者在控制器动作中添加临时测试代码:
```elixirTemporary test — remove after confirming
Temporary test — remove after confirming
def index(conn, _params) do
Sentry.capture_message("Sentry Elixir SDK test event")
text(conn, "sent")
end
Check 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
---def index(conn, _params) do
Sentry.capture_message("Sentry Elixir SDK test event")
text(conn, "sent")
end
几秒内查看Sentry控制台。如果没有收到事件:
1. 设置`config :sentry, log_level: :debug`以查看详细SDK日志
2. 验证`SENTRY_DSN`已正确设置且项目存在
3. 确认`:environment_name`未被Sentry的告警规则过滤
---Phase 4: Cross-Link
阶段4:跨端配置建议
After completing Elixir setup, check for a companion frontend missing Sentry coverage:
bash
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 | |
| Svelte / SvelteKit | |
| Vue | See docs.sentry.io/platforms/javascript/guides/vue/ |
| Other JS/TS | |
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.
完成Elixir端配置后,检查是否存在未配置Sentry的配套前端:
bash
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"'如果发现存在前端目录但未配置Sentry,建议使用对应的技能:
| 检测到的前端框架 | 推荐技能 |
|---|---|
| React / Next.js | |
| Svelte / SvelteKit | |
| Vue | 查看docs.sentry.io/platforms/javascript/guides/vue/ |
| 其他JS/TS框架 | |
将Phoenix后端与JavaScript前端通过关联的Sentry项目连接,可实现分布式链路追踪——在单个追踪视图中展示从浏览器、Phoenix HTTP服务器到下游服务的完整栈追踪。
Troubleshooting
故障排查
| Issue | Solution |
|---|---|
| Events not appearing | Verify |
| Missing stack traces on captured exceptions | Pass |
| |
| Source code context missing in production | Run |
| Context not appearing on async events | |
| Oban integration not reporting crons | Requires Oban v2.17.6+ or Oban Pro; cron jobs must have |
| Duplicate events from Cowboy crashes | Set |
| Ensure |
| JSON encoding error | Add |
| 问题 | 解决方案 |
|---|---|
| 事件未出现在Sentry控制台 | 验证 |
| 捕获的异常缺少栈追踪 | 在 |
| |
| 生产环境中缺少源代码上下文 | 构建OTP发布包前运行 |
| 异步事件中缺少上下文 | |
| Oban集成未上报定时任务 | 需Oban v2.17.6+或Oban Pro;定时任务需在元数据中设置 |
| Cowboy崩溃导致重复事件 | 在 |
| 确保依赖中包含 |
| JSON编码错误 | 若使用Elixir < 1.18,添加 |