Skip to content

Коллекторы

Коллекторы -- основной механизм сбора данных в ADP. Каждый коллектор реализует интерфейс CollectorInterfaceAppDevPanel\Kernel\Collector\CollectorInterfaceDebug data collector responsibility is to collect data during application lifecycle.Kernel · interface и отвечает за захват определённого типа данных во время выполнения приложения.

Встроенные коллекторы

Основные коллекторы

КоллекторСобираемые данные
LogCollectorAppDevPanel\Kernel\Collector\LogCollectorCollects Log data during application lifecycle.Kernel · class · implements SummaryCollectorInterfacePSR-3 сообщения логов (уровень, текст, контекст)
EventCollectorAppDevPanel\Kernel\Collector\EventCollectorCollects Event data during application lifecycle.final Kernel · class · implements SummaryCollectorInterfacePSR-14 отправленные события и слушатели
ExceptionCollectorAppDevPanel\Kernel\Collector\ExceptionCollectorCollects Exception data during application lifecycle.final Kernel · class · implements SummaryCollectorInterfaceНеобработанные исключения со стектрейсами
HttpClientCollectorAppDevPanel\Kernel\Collector\HttpClientCollectorCollects Http Client data during application lifecycle.final Kernel · class · implements SummaryCollectorInterfacePSR-18 исходящие HTTP-запросы и ответы
DatabaseCollectorAppDevPanel\Kernel\Collector\DatabaseCollectorCaptures SQL queries and transactions from the application.final Kernel · class · implements SummaryCollectorInterfaceSQL-запросы, время выполнения, транзакции
ElasticsearchCollectorAppDevPanel\Kernel\Collector\ElasticsearchCollectorCaptures Elasticsearch requests from the application.final Kernel · class · implements SummaryCollectorInterfaceЗапросы к Elasticsearch, тайминг, количество hits
CacheCollectorAppDevPanel\Kernel\Collector\CacheCollectorCaptures cache operations (get, set, delete) across any caching backend.final Kernel · class · implements SummaryCollectorInterfaceОперации кеша с отслеживанием hit/miss
RedisCollectorAppDevPanel\Kernel\Collector\RedisCollectorCaptures Redis commands (GET, SET, DEL, etc.) across any Redis client.final Kernel · class · implements SummaryCollectorInterfaceRedis-команды с таймингом и отслеживанием ошибок
MailerCollectorAppDevPanel\Kernel\Collector\MailerCollectorCaptures email messages sent by the application.final Kernel · class · implements SummaryCollectorInterfaceОтправленные email-сообщения
TranslatorCollectorAppDevPanel\Kernel\Collector\TranslatorCollectorCaptures translation lookups during request execution.final Kernel · class · implements SummaryCollectorInterfaceОбращения к переводам, отсутствующие переводы
QueueCollectorAppDevPanel\Kernel\Collector\QueueCollectorCaptures message queue and message bus operations.final Kernel · class · implements SummaryCollectorInterfaceОперации очереди сообщений (push, consume, fail)
ServiceCollectorAppDevPanel\Kernel\Collector\ServiceCollectorCollects Service data during application lifecycle.final Kernel · class · implements SummaryCollectorInterfaceРазрешение сервисов DI-контейнера
RouterCollectorAppDevPanel\Kernel\Collector\RouterCollectorCaptures HTTP routing data: matched route, match timing, route tree.final Kernel · class · implements SummaryCollectorInterfaceДанные маршрутизации HTTP-запросов
MiddlewareCollectorAppDevPanel\Kernel\Collector\MiddlewareCollectorCaptures HTTP middleware stack execution data.final Kernel · class · implements SummaryCollectorInterfaceВыполнение и тайминг стека middleware
ValidatorCollectorAppDevPanel\Kernel\Collector\ValidatorCollectorCaptures validation operations with results.final Kernel · class · implements SummaryCollectorInterfaceОперации валидации и результаты
AuthorizationCollectorAppDevPanel\Kernel\Collector\AuthorizationCollectorCaptures authentication and authorization data.final Kernel · class · implements SummaryCollectorInterfaceАутентификация и авторизация
TemplateCollectorAppDevPanel\Kernel\Collector\TemplateCollectorCaptures template/view rendering with optional timing, output, parameters, and duplicate detection.final Kernel · class · implements SummaryCollectorInterfaceРендеринг шаблонов/представлений с таймингами, захватом вывода и детекцией дубликатов
VarDumperCollectorAppDevPanel\Kernel\Collector\VarDumperCollectorCollects Var Dumper data during application lifecycle.final Kernel · class · implements SummaryCollectorInterfaceРучные вызовы dump() / dd()
TimelineCollectorAppDevPanel\Kernel\Collector\TimelineCollectorCollects Timeline data during application lifecycle.final Kernel · class · implements SummaryCollectorInterfaceКросс-коллекторная временная шкала производительности
EnvironmentCollectorAppDevPanel\Kernel\Collector\EnvironmentCollectorCollects runtime environment information: PHP version, extensions, SAPI, OS, working directory, server parameters, and environment variables.final Kernel · class · implements SummaryCollectorInterfaceИнформация об окружении PHP и ОС
DeprecationCollectorAppDevPanel\Kernel\Collector\DeprecationCollectorCollects Deprecation data during application lifecycle.final Kernel · class · implements SummaryCollectorInterfaceПредупреждения PHP о депрекациях
OpenTelemetryCollectorAppDevPanel\Kernel\Collector\OpenTelemetryCollectorCollects Open Telemetry data during application lifecycle.final Kernel · class · implements SummaryCollectorInterfaceСпаны и трейсы OpenTelemetry
AssetBundleCollectorAppDevPanel\Kernel\Collector\AssetBundleCollectorCaptures registered asset bundles from the application.final Kernel · class · implements SummaryCollectorInterfaceБандлы фронтенд-ассетов (Yii)
FilesystemStreamCollectorAppDevPanel\Kernel\Collector\Stream\FilesystemStreamCollectorCollects Filesystem Stream data during application lifecycle.final Kernel · class · implements SummaryCollectorInterfaceОперации файловых потоков
HttpStreamCollectorAppDevPanel\Kernel\Collector\Stream\HttpStreamCollectorCollects Http Stream data during application lifecycle.final Kernel · class · implements SummaryCollectorInterfaceОперации HTTP-потоков
CodeCoverageCollectorAppDevPanel\Kernel\Collector\CodeCoverageCollectorCollects Code Coverage data during application lifecycle.final Kernel · class · implements SummaryCollectorInterfaceПострочное покрытие PHP-кода за запрос (требуется pcov или xdebug)

Веб-специфичные

КоллекторСобираемые данные
RequestCollectorAppDevPanel\Kernel\Collector\Web\RequestCollectorCollects Request data during application lifecycle.final Kernel · class · implements SummaryCollectorInterfaceВходящие HTTP-запросы и ответы
WebAppInfoCollectorAppDevPanel\Kernel\Collector\Web\WebAppInfoCollectorCollects Web App Info data during application lifecycle.final Kernel · class · implements SummaryCollectorInterfaceВерсия PHP, память, время выполнения

Консольные

КоллекторСобираемые данные
CommandCollectorAppDevPanel\Kernel\Collector\Console\CommandCollectorCollects Command data during application lifecycle.final Kernel · class · implements SummaryCollectorInterfaceВыполнение консольных команд
ConsoleAppInfoCollectorAppDevPanel\Kernel\Collector\Console\ConsoleAppInfoCollectorCollects Console App Info data during application lifecycle.final Kernel · class · implements SummaryCollectorInterfaceМетаданные консольного приложения

CollectorInterface

Каждый коллектор реализует пять методов:

php
interface CollectorInterface
{
    public function getId(): string;       // Уникальный ID (обычно FQCN)
    public function getName(): string;     // Короткое читаемое имя
    public function startup(): void;       // Вызывается в начале запроса
    public function shutdown(): void;      // Вызывается в конце запроса
    public function getCollected(): array; // Возвращает собранные данные
}

DebuggerAppDevPanel\Kernel\DebuggerClass Debugger.final Kernel · class вызывает startup() на всех зарегистрированных коллекторах в начале запроса, а shutdown() и getCollected() -- в конце.

Создание пользовательского коллектора

php
<?php

declare(strict_types=1);

namespace App\Debug;

use AppDevPanel\Kernel\Collector\CollectorInterface;

final class MetricsCollector implements CollectorInterface
{
    private array $metrics = [];

    public function getId(): string
    {
        return self::class;
    }

    public function getName(): string
    {
        return 'metrics';
    }

    public function startup(): void
    {
        $this->metrics = [];
    }

    public function shutdown(): void
    {
        // Финализация данных при необходимости
    }

    public function getCollected(): array
    {
        return $this->metrics;
    }

    public function record(string $name, float $value): void
    {
        $this->metrics[] = ['name' => $name, 'value' => $value];
    }
}

Зарегистрируйте коллектор в DI-конфигурации адаптера вашего фреймворка, чтобы DebuggerAppDevPanel\Kernel\DebuggerClass Debugger.final Kernel · class подхватил его автоматически.

Поток данных

Коллекторы получают данные двумя способами:

  1. Через прокси -- прокси PSR-интерфейсов (например, LoggerInterfaceProxyAppDevPanel\Kernel\Collector\LoggerInterfaceProxyDecorator proxy for Logger Interface. Intercepts calls and forwards data to collectors.final Kernel · class · implements LoggerInterface) перехватывают вызовы и автоматически передают данные соответствующему коллектору.
  2. Через прямые вызовы -- хуки адаптера или код приложения вызывают методы коллектора напрямую (например, DatabaseCollectorAppDevPanel\Kernel\Collector\DatabaseCollectorCaptures SQL queries and transactions from the application.final Kernel · class · implements SummaryCollectorInterface получает данные запросов через хуки базы данных фреймворка).

SummaryCollectorInterface

Коллекторы также могут реализовать SummaryCollectorInterfaceAppDevPanel\Kernel\Collector\SummaryCollectorInterfaceSummary data collector responsibility is to collect summary data for a collector. Summary is used to display a list of previous requests and select one to display full info. Its data set is specific to the list and is reduced compared to full data collected in {@see CollectorInterface}.Kernel · interface · extends CollectorInterface для предоставления сводных данных, отображаемых в списке отладочных записей без загрузки полных данных коллектора.

TranslatorCollector

Захватывает обращения к переводам во время выполнения запроса, включая обнаружение отсутствующих переводов. Реализует SummaryCollectorInterfaceAppDevPanel\Kernel\Collector\SummaryCollectorInterfaceSummary data collector responsibility is to collect summary data for a collector. Summary is used to display a list of previous requests and select one to display full info. Its data set is specific to the list and is reduced compared to full data collected in {@see CollectorInterface}.Kernel · interface · extends CollectorInterface.

Подробности на странице Переводчик: поля TranslationRecord, структура собранных данных, логика определения отсутствующих переводов, интеграции proxy фреймворков и примеры конфигурации.

Code Coverage Collector

CodeCoverageCollectorAppDevPanel\Kernel\Collector\CodeCoverageCollectorCollects Code Coverage data during application lifecycle.final Kernel · class · implements SummaryCollectorInterface собирает построчное покрытие PHP-кода за каждый HTTP-запрос, используя pcov или xdebug в качестве драйвера.

Предварительные требования

Необходимо расширение pcov (рекомендуется) или xdebug с включённым режимом coverage. Без них коллектор возвращает пустой результат с driver: null.

Как это работает

  1. При startup() коллектор определяет доступный драйвер и запускает сбор покрытия
  2. Код приложения выполняется в обычном режиме — каждая выполненная строка PHP отслеживается
  3. При shutdown() сбор останавливается, и сырые данные обрабатываются в постатистику по файлам
  4. Файлы, соответствующие excludePaths (по умолчанию: vendor), отфильтровываются

Включение

Покрытие кода — opt-in (по умолчанию отключено) из-за влияния на производительность.

yaml
# config/packages/app_dev_panel.yaml
app_dev_panel:
    collectors:
        code_coverage: true

Формат вывода

json
{
    "driver": "pcov",
    "files": {
        "/app/src/Controller/HomeController.php": {
            "coveredLines": 12,
            "executableLines": 15,
            "percentage": 80.0
        }
    },
    "summary": {
        "totalFiles": 42,
        "coveredLines": 340,
        "executableLines": 500,
        "percentage": 68.0
    }
}

Эндпоинт Inspector

Inspector также предоставляет эндпоинт GET /inspect/api/coverage для разового сбора покрытия. Подробнее — в разделе Эндпоинты Inspector.

Выпущено под лицензией MIT.