PHP项目Telescope调试工具

wen PHP项目 2

PHP项目Telescope调试工具详解

Telescope 是 Laravel 生态系统中一个强大的调试和监控工具,主要用于开发阶段的调试和问题排查。

PHP项目Telescope调试工具

主要功能

  1. 请求监控

    • 记录所有 HTTP 请求
    • 查看请求参数、响应内容
    • 跟踪请求执行时间
  2. 数据库查询

    • 记录所有 SQL 查询
    • 查看查询耗时
    • 支持查询参数绑定
  3. 日志查看

    • 集中管理应用日志
    • 按级别筛选(debug、info、error 等)
    • 实时日志查看
  4. 异常追踪

    • 记录异常信息
    • 堆栈跟踪
    • 请求上下文
  5. 邮件监控

    • 查看发送的邮件
    • 预览邮件内容
    • 调试邮件模板
  6. 队列任务

    • 监控队列作业
    • 查看执行状态
    • 调试失败任务
  7. 事件和缓存

    • 跟踪事件触发
    • 缓存操作记录
    • Redis 命令监控

安装配置

# 安装 Telescope
composer require laravel/telescope --dev
# 发布资源
php artisan telescope:install
# 运行迁移
php artisan migrate

基础使用示例

// 在控制器中使用
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
    public function index()
    {
        // Telescope 会自动记录这个请求
        $users = User::where('active', true)
                     ->orderBy('created_at', 'desc')
                     ->get();
        // 手动添加标签
        app('telescope')->tag('users:list');
        return response()->json($users);
    }
    public function store(Request $request)
    {
        // 自定义记录
        telescope()->record('user_creation', [
            'email' => $request->email,
            'name' => $request->name
        ]);
        // 添加自定义标签
        telescope()->tag(['user_created', 'admin_action']);
        $user = User::create($request->validated());
        return response()->json($user, 201);
    }
}

高级用法

自定义监控

// 创建自定义门面
use Illuminate\Support\Facades\Facade;
class Telescope extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'telescope';
    }
}
// 在代码中使用
Telescope::record('custom_event', [
    'user_id' => auth()->id(),
    'action' => 'export_data',
    'records_count' => 100
]);

条件记录

// 只在特定条件下记录
if (app()->environment('local')) {
    telescope()->record('debug_info', [
        'memory_usage' => memory_get_usage(true),
        'execution_time' => microtime(true) - LARAVEL_START
    ]);
}

自定义标签和过滤

// 配置文件 config/telescope.php
return [
    'watchers' => [
        Watchers\RequestWatcher::class => [
            'enabled' => env('TELESCOPE_ENABLED', true),
            'size_limit' => env('TELESCOPE_RESPONSE_SIZE_LIMIT', 64),
        ],
        // 可以禁用某些 Watcher
        Watchers\DumpWatcher::class => false,
    ],
    // 标签过滤器
    'tag_filter' => [
        'App\\' => true,
        'auth' => true,
    ],
];

实际应用场景

场景1:调试 API 请求

// API 控制器
class ApiController extends Controller
{
    public function complexOperation(Request $request)
    {
        // Telescope 会自动记录所有数据库查询
        $result = DB::transaction(function () use ($request) {
            // 复杂业务逻辑
            $user = User::findOrFail($request->user_id);
            $order = Order::create([...]);
            // 查看生成的 SQL 和性能
            return compact('user', 'order');
        });
        return response()->json($result);
    }
}

场景2:邮件调试

// 查看邮件发送情况
Mail::to($user->email)->send(new OrderConfirmation($order));
// Telescope 会记录邮件内容,无需实际发送

安全配置

// 生产环境配置
'gate' => [
    'enabled' => true,
    'email' => ['admin@example.com'],  // 仅允许特定用户访问
    'ips' => ['127.0.0.1'],            // 仅允许本地 IP
],
// 或在 AppServiceProvider 中
use Laravel\Telescope\Telescope;
public function boot()
{
    Telescope::auth(function ($request) {
        return $request->user() && 
               $request->user()->isAdmin();
    });
}

性能优化建议

  1. 仅开发环境启用

    # .env 文件
    TELESCOPE_ENABLED=false  # 生产环境禁用
  2. 限制记录数量

    // config/telescope.php
    'storage' => [
        'count' => 1000,  // 保留最近1000条记录
    ],
  3. 清理旧数据

    # 定期清理
    php artisan telescope:prune --days=7

最佳实践

  1. 结合调试辅助函数

    // 使用 dd() 和 dump()
    dd($variable);  // Telescope 会捕获
    dump($variable); // 在 Telescope 中查看
  2. 使用标签分类

    // 按业务模块标记
    telescope()->tag(['payment', 'failed_transaction']);
    telescope()->tag(['auth', 'login_attempt']);
  3. 监控关键操作

    // 记录重要操作
    public function criticalOperation()
    {
        telescope()->record('critical_action', [
            'timestamp' => now(),
            'user' => auth()->user()->email,
            'action' => 'delete_user',
            'target' => $userId
        ]);
    }

Telescope 是 Laravel 开发的得力助手,合理使用可以显著提高开发和调试效率,记住在生产环境谨慎使用,避免性能影响和数据泄露风险。

抱歉,评论功能暂时关闭!