sentry-php-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAll Skills > SDK Setup > PHP SDK
所有技能 > SDK 配置 > PHP SDK
Sentry PHP SDK
Sentry PHP SDK
Opinionated wizard that scans your PHP project and guides you through complete Sentry setup.
这是一套开箱即用的配置向导,可以扫描你的PHP项目,引导你完成Sentry的全流程配置。
Invoke This Skill When
适用场景
- User asks to "add Sentry to PHP" or "setup Sentry" in a PHP app
- User wants error monitoring, tracing, profiling, logging, metrics, or crons in PHP
- User mentions ,
sentry/sentry,sentry/sentry-laravel, or Sentry + any PHP frameworksentry/sentry-symfony - User wants to monitor Laravel routes, Symfony controllers, queues, scheduled tasks, or plain PHP scripts
Note: SDK versions and APIs below reflect Sentry docs at time of writing (sentry/sentry 4.x, sentry/sentry-laravel 4.x, sentry/sentry-symfony 5.x). Always verify against docs.sentry.io/platforms/php/ before implementing.
- 用户要求给PHP应用「添加Sentry」或「配置Sentry」
- 用户需要在PHP中实现错误监控、链路追踪、性能剖析、日志记录、指标统计或定时任务监控
- 用户提到 、
sentry/sentry、sentry/sentry-laravel,或者Sentry搭配任意PHP框架的需求sentry/sentry-symfony - 用户需要监控Laravel路由、Symfony控制器、队列、定时任务或原生PHP脚本
注意: 下文提到的SDK版本和API对应编写时的Sentry官方文档(sentry/sentry 4.x、sentry/sentry-laravel 4.x、sentry/sentry-symfony 5.x)。 实施前请务必参考 docs.sentry.io/platforms/php/ 确认最新规范。
Phase 1: Detect
阶段1:项目检测
Run these commands to understand the project before making recommendations:
bash
undefined在给出配置建议前,先运行以下命令了解项目情况:
bash
undefinedCheck existing Sentry
检查是否已安装Sentry
grep -i sentry composer.json composer.lock 2>/dev/null
grep -i sentry composer.json composer.lock 2>/dev/null
Detect framework
检测使用的框架
cat composer.json | grep -E '"laravel/framework"|"symfony/framework-bundle"|"illuminate/'
cat composer.json | grep -E '"laravel/framework"|"symfony/framework-bundle"|"illuminate/'
Confirm framework via filesystem markers
通过文件系统标记确认框架
ls artisan 2>/dev/null && echo "Laravel detected"
ls bin/console 2>/dev/null && echo "Symfony detected"
ls artisan 2>/dev/null && echo "检测到Laravel"
ls bin/console 2>/dev/null && echo "检测到Symfony"
Detect queue systems
检测队列系统
grep -E '"laravel/horizon"|"symfony/messenger"' composer.json 2>/dev/null
grep -E '"laravel/horizon"|"symfony/messenger"' composer.json 2>/dev/null
Detect AI libraries
检测AI相关库
grep -E '"openai-php|"openai/|anthropic|llm' composer.json 2>/dev/null
grep -E '"openai-php|"openai/|anthropic|llm' composer.json 2>/dev/null
Check for companion frontend
检查是否有配套前端项目
ls frontend/ resources/js/ assets/ 2>/dev/null
cat package.json 2>/dev/null | grep -E '"react"|"svelte"|"vue"|"next"'
**What to note:**
- Is `sentry/sentry` (or `-laravel` / `-symfony`) already in `composer.json`? If yes, check if the init call exists — may just need feature config.
- Framework detected? **Laravel** (has `artisan` + `laravel/framework` in composer.json), **Symfony** (has `bin/console` + `symfony/framework-bundle`), or **plain PHP**.
- Queue system? (Laravel Queue / Horizon, Symfony Messenger need queue worker configuration.)
- AI libraries? (No PHP AI auto-instrumentation yet — document manually if needed.)
- Companion frontend? (Triggers Phase 4 cross-link.)
---ls frontend/ resources/js/ assets/ 2>/dev/null
cat package.json 2>/dev/null | grep -E '"react"|"svelte"|"vue"|"next"'
**需要记录的信息:**
- `composer.json` 中是否已经存在 `sentry/sentry`(或对应 `-laravel` / `-symfony` 包)?如果已存在,检查是否有初始化调用,可能只需要补充功能配置即可。
- 检测到的框架类型:**Laravel**(composer.json存在`laravel/framework`且有`artisan`文件)、**Symfony**(composer.json存在`symfony/framework-bundle`且有`bin/console`文件),或是**原生PHP**。
- 是否使用队列系统?(Laravel Queue/Horizon、Symfony Messenger需要额外配置队列工作进程)
- 是否使用AI相关库?(目前PHP还没有AI自动埋点能力,如有需要请手动记录)
- 是否有配套前端项目?(触发阶段4的关联配置推荐)
---Phase 2: Recommend
阶段2:方案推荐
Based on what you found, present a concrete proposal. Don't ask open-ended questions — lead with a recommendation:
Always recommended (core coverage):
- ✅ Error Monitoring — captures unhandled exceptions and PHP errors
- ✅ Logging — Monolog integration (Laravel/Symfony auto-configure; plain PHP uses )
MonologHandler
Recommend when detected:
- ✅ Tracing — web framework detected (Laravel/Symfony auto-instrument HTTP, DB, Twig/Blade, cache)
- ⚡ Profiling — production apps where performance matters (requires PHP extension, Linux/macOS only)
excimer - ⚡ Crons — scheduler patterns detected (Laravel Scheduler, Symfony Scheduler, custom cron jobs)
- ⚡ Metrics — business KPIs or SLO tracking (beta; uses API)
TraceMetrics
Recommendation matrix:
| Feature | Recommend when... | Reference |
|---|---|---|
| Error Monitoring | Always — non-negotiable baseline | |
| Tracing | Laravel/Symfony detected, or manual spans needed | |
| Profiling | Production + | |
| Logging | Always; Monolog for Laravel/Symfony | |
| Metrics | Business events or SLO tracking needed (beta) | |
| Crons | Scheduler or cron patterns detected | |
Propose: "I recommend Error Monitoring + Tracing [+ Logging]. Want Profiling, Crons, or Metrics too?"
根据你检测到的项目信息,给出具体的配置建议。不要提出开放性问题,先直接给出推荐方案:
默认推荐(基础能力覆盖):
- ✅ 错误监控 — 捕获未处理异常和PHP原生错误
- ✅ 日志记录 — 集成Monolog(Laravel/Symfony会自动配置,原生PHP使用)
MonologHandler
按需推荐的能力:
- ✅ 链路追踪 — 检测到使用Web框架时推荐(Laravel/Symfony可自动对HTTP、数据库、Twig/Blade模板、缓存做埋点)
- ⚡ 性能剖析 — 对性能要求高的生产环境使用(需要安装PHP扩展,仅支持Linux/macOS)
excimer - ⚡ 定时任务监控 — 检测到调度器模式时推荐(Laravel Scheduler、Symfony Scheduler、自定义cron任务)
- ⚡ 指标统计 — 需要统计业务KPI或SLO时使用(beta阶段,使用API)
TraceMetrics
推荐矩阵:
| 功能 | 推荐使用场景 | 参考文档 |
|---|---|---|
| 错误监控 | 默认必选 — 基础监控能力 | |
| 链路追踪 | 检测到Laravel/Symfony,或需要手动埋点时 | |
| 性能剖析 | 生产环境且可用 | |
| 日志记录 | 默认必选;Laravel/Symfony使用Monolog | |
| 指标统计 | 需要统计业务事件或SLO时(beta) | |
| 定时任务监控 | 检测到调度器或cron任务时 | |
可以这样提议:「我推荐配置错误监控+链路追踪[+日志记录]。是否还需要性能剖析、定时任务监控或指标统计能力?」
Phase 3: Guide
阶段3:配置引导
Install
安装依赖
bash
undefinedbash
undefinedPlain PHP
原生PHP
composer require sentry/sentry "^4.0"
composer require sentry/sentry "^4.0"
Laravel
Laravel
composer require sentry/sentry-laravel "^4.0"
composer require sentry/sentry-laravel "^4.0"
Symfony
Symfony
composer require sentry/sentry-symfony "^5.0"
**System requirements:**
- PHP 7.2 or later
- Extensions: `ext-json`, `ext-mbstring`, `ext-curl` (all required)
- `excimer` PECL extension (Linux/macOS only — required for profiling)composer require sentry/sentry-symfony "^5.0"
**系统要求:**
- PHP 7.2 及以上版本
- 必须安装扩展:`ext-json`、`ext-mbstring`、`ext-curl`
- `excimer` PECL扩展(仅Linux/macOS可用,性能剖析功能必填)Framework-Specific Initialization
框架专属初始化配置
Plain PHP
原生PHP
Place at the top of your entry point (, , or equivalent), before any application code:
\Sentry\init()index.phpbootstrap.phpphp
<?php
require_once 'vendor/autoload.php';
\Sentry\init([
'dsn' => $_SERVER['SENTRY_DSN'] ?? '',
'environment' => $_SERVER['SENTRY_ENVIRONMENT'] ?? 'production',
'release' => $_SERVER['SENTRY_RELEASE'] ?? null,
'send_default_pii' => true,
'traces_sample_rate' => 1.0,
'profiles_sample_rate' => 1.0,
'enable_logs' => true,
]);
// rest of application...在入口文件(、或其他等价文件)的最顶部,所有业务代码运行前添加 初始化代码:
index.phpbootstrap.php\Sentry\init()php
<?php
require_once 'vendor/autoload.php';
\Sentry\init([
'dsn' => $_SERVER['SENTRY_DSN'] ?? '',
'environment' => $_SERVER['SENTRY_ENVIRONMENT'] ?? 'production',
'release' => $_SERVER['SENTRY_RELEASE'] ?? null,
'send_default_pii' => true,
'traces_sample_rate' => 1.0,
'profiles_sample_rate' => 1.0,
'enable_logs' => true,
]);
// 后续业务代码...Laravel
Laravel
Step 1 — Register exception handler in :
bootstrap/app.phpphp
use Sentry\Laravel\Integration;
return Application::configure(basePath: dirname(__DIR__))
->withExceptions(function (Exceptions $exceptions) {
Integration::handles($exceptions);
})->create();Step 2 — Publish config and set DSN:
bash
php artisan sentry:publish --dsn=YOUR_DSNThis creates and adds to .
config/sentry.phpSENTRY_LARAVEL_DSN.envStep 3 — Configure :
.envini
SENTRY_LARAVEL_DSN=https://examplePublicKey@o0.ingest.sentry.io/0
SENTRY_TRACES_SAMPLE_RATE=1.0
SENTRY_PROFILES_SAMPLE_RATE=1.0For full Laravel configuration options, read.${SKILL_ROOT}/references/laravel.md
步骤1 — 在 中注册异常处理器:
bootstrap/app.phpphp
use Sentry\Laravel\Integration;
return Application::configure(basePath: dirname(__DIR__))
->withExceptions(function (Exceptions $exceptions) {
Integration::handles($exceptions);
})->create();步骤2 — 发布配置文件并设置DSN:
bash
php artisan sentry:publish --dsn=YOUR_DSN该命令会创建 配置文件,并将 添加到 文件中。
config/sentry.phpSENTRY_LARAVEL_DSN.env步骤3 — 配置 文件:
.envini
SENTRY_LARAVEL_DSN=https://examplePublicKey@o0.ingest.sentry.io/0
SENTRY_TRACES_SAMPLE_RATE=1.0
SENTRY_PROFILES_SAMPLE_RATE=1.0完整的Laravel配置选项请参考。${SKILL_ROOT}/references/laravel.md
Symfony
Symfony
Step 1 — Register the bundle in (auto-done by Symfony Flex):
config/bundles.phpphp
Sentry\SentryBundle\SentryBundle::class => ['all' => true],Step 2 — Create :
config/packages/sentry.yamlyaml
sentry:
dsn: '%env(SENTRY_DSN)%'
options:
environment: '%env(APP_ENV)%'
release: '%env(SENTRY_RELEASE)%'
send_default_pii: true
traces_sample_rate: 1.0
profiles_sample_rate: 1.0
enable_logs: trueStep 3 — Set the DSN in :
.envini
SENTRY_DSN=https://examplePublicKey@o0.ingest.sentry.io/0For full Symfony configuration options, read.${SKILL_ROOT}/references/symfony.md
步骤1 — 在 中注册bundle(Symfony Flex会自动完成该步骤):
config/bundles.phpphp
Sentry\SentryBundle\SentryBundle::class => ['all' => true],步骤2 — 创建 配置文件:
config/packages/sentry.yamlyaml
sentry:
dsn: '%env(SENTRY_DSN)%'
options:
environment: '%env(APP_ENV)%'
release: '%env(SENTRY_RELEASE)%'
send_default_pii: true
traces_sample_rate: 1.0
profiles_sample_rate: 1.0
enable_logs: true步骤3 — 在 文件中设置DSN:
.envini
SENTRY_DSN=https://examplePublicKey@o0.ingest.sentry.io/0完整的Symfony配置选项请参考。${SKILL_ROOT}/references/symfony.md
Quick Start — Recommended Init (Plain PHP)
快速入门 — 原生PHP推荐初始化配置
Full init enabling the most features with sensible defaults:
php
\Sentry\init([
'dsn' => $_SERVER['SENTRY_DSN'] ?? '',
'environment' => $_SERVER['SENTRY_ENVIRONMENT'] ?? 'production',
'release' => $_SERVER['SENTRY_RELEASE'] ?? null,
'send_default_pii' => true,
// Tracing (lower to 0.1–0.2 in high-traffic production)
'traces_sample_rate' => 1.0,
// Profiling — requires excimer extension (Linux/macOS only)
'profiles_sample_rate' => 1.0,
// Structured logs (sentry/sentry >=4.12.0)
'enable_logs' => true,
]);以下是开启大部分常用功能的合理默认配置:
php
\Sentry\init([
'dsn' => $_SERVER['SENTRY_DSN'] ?? '',
'environment' => $_SERVER['SENTRY_ENVIRONMENT'] ?? 'production',
'release' => $_SERVER['SENTRY_RELEASE'] ?? null,
'send_default_pii' => true,
// 链路追踪采样率(高流量生产环境建议调低到0.1–0.2)
'traces_sample_rate' => 1.0,
// 性能剖析 — 需要安装excimer扩展(仅支持Linux/macOS)
'profiles_sample_rate' => 1.0,
// 结构化日志(需要sentry/sentry >=4.12.0)
'enable_logs' => true,
]);For Each Agreed Feature
已确认启用的功能配置
Walk through features one at a time. Load the reference, follow its steps, verify before moving on:
| Feature | Reference file | Load when... |
|---|---|---|
| Error Monitoring | | Always (baseline) |
| Tracing | | HTTP handlers / distributed tracing |
| Profiling | | Performance-sensitive production |
| Logging | | Always; Monolog for Laravel/Symfony |
| Metrics | | Business KPIs / SLO tracking (beta) |
| Crons | | Scheduler / cron patterns detected |
For each feature: , follow steps exactly, verify it works.
Read ${SKILL_ROOT}/references/<feature>.md逐个配置你需要的功能,加载对应参考文档,按步骤操作,验证通过后再进行下一个功能的配置:
| 功能 | 参考文档 | 启用场景 |
|---|---|---|
| 错误监控 | | 默认必选(基础能力) |
| 链路追踪 | | HTTP服务/分布式链路追踪需求 |
| 性能剖析 | | 对性能敏感的生产环境 |
| 日志记录 | | 默认必选;Laravel/Symfony使用Monolog |
| 指标统计 | | 业务KPI/SLO统计需求(beta) |
| 定时任务监控 | | 检测到调度器或cron任务时 |
对每个功能:,严格按步骤操作,验证功能正常后再继续。
读取 ${SKILL_ROOT}/references/<功能名>.mdConfiguration Reference
配置参考
Key \Sentry\init()
Options (Plain PHP)
\Sentry\init()\Sentry\init()
核心配置项(原生PHP)
\Sentry\init()| Option | Type | Default | Purpose |
|---|---|---|---|
| | | SDK disabled if empty or |
| | | e.g., |
| | | e.g., |
| | | Include request headers, cookies, IP |
| | | Error event sample rate (0.0–1.0) |
| | | Transaction sample rate; |
| | | Custom per-transaction sampling (overrides rate) |
| | | Profiling rate relative to traces; requires |
| | | Send structured logs to Sentry (>=4.12.0) |
| | | Max breadcrumbs per event |
| | | Stack traces on |
| | | Path prefixes belonging to your app |
| | | Path prefixes for third-party code (hidden in traces) |
| | | Exception FQCNs to never report |
| | | Transaction names to never report |
| | | PHP error bitmask (e.g., |
| | | Capture errors suppressed by |
| | | |
| | identity | |
| | identity | |
| | | Downstream hosts to inject |
| | | Verbose SDK output (use a PSR-3 |
| 配置项 | 类型 | 默认值 | 作用 |
|---|---|---|---|
| | | 为空或 |
| | | 环境标识,例如 |
| | | 版本标识,例如 |
| | | 是否包含请求头、Cookie、IP等用户标识信息 |
| | | 错误事件采样率(范围0.0–1.0) |
| | | 链路追踪采样率;为 |
| | | 自定义链路采样逻辑(覆盖固定采样率) |
| | | 性能剖析采样率(基于链路追踪采样结果);需要 |
| | | 发送结构化日志到Sentry(需要>=4.12.0版本) |
| | | 每个事件最多保留的面包屑数量 |
| | | 调用 |
| | | 属于业务代码的路径前缀 |
| | | 第三方代码的路径前缀(链路追踪中会隐藏) |
| | | 不需要上报的异常类全限定名 |
| | | 不需要上报的事务名称 |
| | | PHP错误掩码,例如 |
| | | 是否上报被 |
| | | 请求体采集大小: |
| | identity | |
| | identity | |
| | | 需要注入 |
| | | 开启SDK详细日志输出(建议使用PSR-3 |
Environment Variables
环境变量
| Variable | Maps to | Notes |
|---|---|---|
| | Also |
| | |
| | Also reads |
| |
Laravel note: Uses(falls back toSENTRY_LARAVEL_DSN). Other options followSENTRY_DSN,SENTRY_TRACES_SAMPLE_RATE, etc.SENTRY_PROFILES_SAMPLE_RATE
| 环境变量 | 对应配置项 | 说明 |
|---|---|---|
| | 也会从 |
| | |
| | 也会读取 |
| |
Laravel注意事项: 使用(会 fallback 到SENTRY_LARAVEL_DSN),其他配置项对应SENTRY_DSN、SENTRY_TRACES_SAMPLE_RATE等格式。SENTRY_PROFILES_SAMPLE_RATE
Verification
配置验证
Test that Sentry is receiving events:
php
// Trigger a real error event — check the Sentry dashboard within seconds
throw new \Exception('Sentry PHP SDK test');Or for a non-crashing check:
php
\Sentry\captureMessage('Sentry PHP SDK test');Laravel:
bash
php artisan sentry:testIf nothing appears:
- Enable debug output:
php
\Sentry\init([ 'dsn' => '...', 'logger' => new \Sentry\Logger\DebugStdOutLogger(), ]); - Verify the DSN is correct (format: )
https://<key>@o<org>.ingest.sentry.io/<project> - Check (or
SENTRY_DSN) env var is set in the running processSENTRY_LARAVEL_DSN - For queue workers: ensure Sentry is initialized inside the worker process, not just the web process
测试Sentry是否能正常接收事件:
php
// 触发一个真实错误事件 — 几秒内即可在Sentry控制台看到上报结果
throw new \Exception('Sentry PHP SDK 测试');如果不想让程序崩溃,可以使用以下方式测试:
php
\Sentry\captureMessage('Sentry PHP SDK 测试');Laravel专属测试命令:
bash
php artisan sentry:test如果控制台没有收到事件:
- 开启调试输出:
php
\Sentry\init([ 'dsn' => '...', 'logger' => new \Sentry\Logger\DebugStdOutLogger(), ]); - 验证DSN格式正确(格式:)
https://<key>@o<org>.ingest.sentry.io/<project> - 检查运行进程中是否正确设置了(或
SENTRY_DSN)环境变量SENTRY_LARAVEL_DSN - 队列工作进程场景:确保Sentry在队列工作进程内部初始化,而不是仅在Web进程中初始化
Phase 4: Cross-Link
阶段4:关联配置推荐
After completing PHP setup, check for a companion frontend missing Sentry:
bash
ls frontend/ resources/js/ assets/ public/ 2>/dev/null
cat package.json frontend/package.json 2>/dev/null \
| grep -E '"react"|"svelte"|"vue"|"next"|"nuxt"'If a frontend exists without Sentry, suggest the matching skill:
| Frontend detected | Suggest skill |
|---|---|
| React / Next.js | |
| Svelte / SvelteKit | |
| Vue / Nuxt | Use |
| Other JS/TS | |
完成PHP侧配置后,检查是否有未配置Sentry的配套前端项目:
bash
ls frontend/ resources/js/ assets/ public/ 2>/dev/null
cat package.json frontend/package.json 2>/dev/null \
| grep -E '"react"|"svelte"|"vue"|"next"|"nuxt"'如果存在未配置Sentry的前端项目,推荐使用对应配置技能:
| 检测到的前端框架 | 推荐技能 |
|---|---|
| React / Next.js | |
| Svelte / SvelteKit | |
| Vue / Nuxt | 使用 |
| 其他JS/TS项目 | |
Troubleshooting
问题排查
| Issue | Solution |
|---|---|
| Events not appearing | Enable |
| Malformed DSN error | Format: |
| Laravel exceptions not captured | Ensure |
| Symfony exceptions not captured | Verify |
| No traces appearing | Set |
| Profiling not working | |
| Requires |
| Queue worker errors missing | Init Sentry in the worker process itself, not just the web process; for Laravel use |
| Too many transactions | Lower |
| PII not captured | Set |
| Set |
| Cross-service traces broken | Check |
| 问题 | 解决方案 |
|---|---|
| 控制台收不到事件 | 开启 |
| DSN格式错误 | 正确格式为: |
| Laravel异常没有被捕获 | 确认 |
| Symfony异常没有被捕获 | 确认 |
| 没有链路追踪数据 | 确保 |
| 性能剖析不生效 | 需要安装 |
| 需要 |
| 队列工作进程错误没有上报 | 在队列工作进程自身的配置中初始化Sentry,不要仅在Web进程中配置;Laravel场景下确保工作进程的 |
| 事务上报数量过多 | 调低 |
| 用户标识信息没有被采集 | 配置 |
被 | 配置 |
| 跨服务链路不通 | 检查 |