laravel-debugbar README

The project's README from github.com/fruitcake/laravel-debugbar. As one markdown file: README.md.

Debugbar for Laravel

Unit Tests Packagist License Latest Stable Version Total Downloads Fruitcake

This is a package to integrate PHP Debug Bar with Laravel. It includes a ServiceProvider to register the debugbar and attach it to the output. You can publish assets and configure it through Laravel. It bootstraps some Collectors to work with Laravel and implements a couple custom DataCollectors, specific for Laravel. It is configured to display Redirects and Ajax/Livewire Requests, which are shown in a dropdown. Read the documentation for more configuration options.

Debugbar Dark Mode screenshot

[!CAUTION] Use the DebugBar only in development. Do not use Debugbar on publicly accessible websites, as it will leak information from stored requests (by design).

[!WARNING] It can also slow the application down (because it has to gather and render data). So when experiencing slowness, try disabling some of the collectors.

This package includes some custom collectors:

Bootstraps the following collectors for Laravel:

And the default collectors:

It also provides a facade interface (Debugbar) for easy logging Messages, Exceptions and Time

Installation

Require this package with composer. It is recommended to only require the package for development.

composer require fruitcake/laravel-debugbar --dev

Note: The package name has changed to fruitcake/laravel-debugbar. If you're using barryvdh/laravel-debugbar, you can safely replace this with the new package name: composer remove barryvdh/laravel-debugbar --dev --no-scripts

Laravel uses Package Auto-Discovery, so doesn't require you to manually add the ServiceProvider.

The Debugbar will be enabled when APP_DEBUG is true and when the environment is not production or testing.

You can disable it in the config (debugbar.enabled) or by setting DEBUGBAR_ENABLED in your .env. See more options in config/debugbar.php You can also set in your config if you want to include/exclude the vendor files also (FontAwesome, Highlight.js and jQuery). If you already use them in your site, set it to false. You can also only display the js or css vendors, by setting it to 'js' or 'css'. (Highlight.js requires both css + js, so set to true for syntax highlighting)

Copy the package config to your local config with the publish command:

php artisan vendor:publish --provider='Fruitcake\LaravelDebugbar\ServiceProvider'

Laravel with Octane:

Laravel Debugbar 4.x works out of the box with Octane. No need to add anything to your config.

If you're upgrading from Laravel Debugbar 3.x, remove the 'flush' config for Debugbar in config/octane.php.

Usage

You can now add messages using the Facade (when added), using the PSR-3 levels (debug, info, notice, warning, error, critical, alert, emergency):

Debugbar::info($object);
Debugbar::error('Error!');
Debugbar::warning('Watch out…');
Debugbar::addMessage('Another message', 'mylabel');

And start/stop timing:

Debugbar::startMeasure('render','Time for rendering');
Debugbar::stopMeasure('render');
Debugbar::addMeasure('now', LARAVEL_START, microtime(true));
Debugbar::measure('My long operation', function() {
    // Do something…
});

Or log exceptions:

try {
    throw new Exception('foobar');
} catch (Exception $e) {
    Debugbar::addThrowable($e);
}

There are also helper functions available for the most common calls:

// All arguments will be dumped as a debug message
debug($var1, $someString, $intValue, $object);

// `$collection->debug()` will return the collection and dump it as a debug message. Like `$collection->dump()`
collect([$var1, $someString])->debug();

debugbar()->startMeasure('render','Time for rendering');
debugbar()->stopMeasure('render');
debugbar()->addMeasure('now', LARAVEL_START, microtime(true));
debugbar()->measure('My long operation', function() {
    // Do something…
});

If you want you can add your own DataCollectors, through the Container or the Facade:

Debugbar::addCollector(new DebugBar\DataCollector\MessagesCollector('my_messages'));
// Or via the App container:
$debugbar = App::make('debugbar');
$debugbar->addCollector(new DebugBar\DataCollector\MessagesCollector('my_messages'));

By default, the Debugbar is injected just before </body>. If you want to inject the Debugbar yourself, set the config option 'inject' to false and use the renderer yourself and follow https://php-debugbar.com/docs/rendering

$renderer = Debugbar::getJavascriptRenderer();

Note: Not using the auto-inject, will disable the Request information, because that is added After the response. You can add the default_request datacollector in the config as alternative.

Enabling/Disabling on run time

You can enable or disable the debugbar during run time.

\Debugbar::enable();
\Debugbar::disable();

NB. Once enabled, the collectors are added (and could produce extra overhead), so if you want to use the debugbar in production, disable in the config and only enable when needed.

Note: by default Debugbar can only be enabled in debug mode and non-production environments. It's highly recommended to don't install this in production at all. If you really need to enable it in production, you can set debugbar.force_allow_enable to true, or set DEBUGBAR_FORCE_ALLOW_ENABLE=true in your .env. This will not enable the Debugbar, but will run the ServiceProvider bootstrap so you can enable it after booting.

Storage

Debugbar remembers previous requests, which you can view using the Browse button on the right. This will only work if you enable debugbar.storage.open in the config. Make sure you only do this on local development, because otherwise other people will be able to view previous requests. In general, Debugbar should only be used locally or at least restricted by IP. It's possible to pass a callback, which will receive the Request object, so you can determine access to the OpenHandler storage.

Twig Integration

Laravel Debugbar comes with two Twig Extensions. These are tested with rcrowe/TwigBridge 0.6.x

Add the following extensions to your TwigBridge config/extensions.php (or register the extensions manually)

'Fruitcake\LaravelDebugbar\Twig\Extension\Debug',
'Fruitcake\LaravelDebugbar\Twig\Extension\Dump',
'Fruitcake\LaravelDebugbar\Twig\Extension\Stopwatch',

The Dump extension will replace the dump function to output variables using the DataFormatter. The Debug extension adds a debug() function which passes variables to the Message Collector, instead of showing it directly in the template. It dumps the arguments, or when empty; all context variables.

{{ debug() }}
{{ debug(user, categories) }}

The Stopwatch extension adds a stopwatch tag similar to the one in Symfony/Silex Twigbridge.

{% stopwatch "foo" %}
    …some things that gets timed
{% endstopwatch %}

laravel-debugbar (fruitcake/laravel-debugbar)

Searching Database…

Что это такое?Пакет для Laravel, который встраивает PHP Debug Bar в ваше приложение: ServiceProvider регистрирует debugbar и добавляет на ваши страницы панель отладки, где видны запросы к базе, логи, время выполнения и многое другое.
Это отдельная программа, которую я запускаю сам, или что-то, что добавляется в мой проект на Laravel?Это то, что добавляется в проект: пакет ставится через Composer и запускается внутри Laravel, при этом коллекторы уже настроены под Laravel, а кроме них есть собственные DataCollectors, написанные специально для него.
Нужно ли что-то настраивать, прежде чем панель появится?Нет: панель включается сама, если APP_DEBUG равен true, а окружение не production и не testing. Включать и выключать её можно через настройку debugbar.enabled или переменную DEBUGBAR_ENABLED в файле .env.
Можно ли оставить её включённой в production?Не рекомендуется: она по своей задумке раскрывает информацию из сохранённых запросов и замедляет приложение, пока собирает данные. В README прямо сказано, что в production её вообще не стоит устанавливать; есть флаг force_allow_enable, но он лишь запускает provider, чтобы панель можно было включить во время работы приложения.
Куда попадают записанные им запросы?Предыдущие запросы сохраняются локально, и их можно открыть заново кнопкой Browse, но только если включена настройка debugbar.storage.open. В README предупреждают, что это стоит держать только для локальной разработки, иначе чужие люди смогут смотреть прошлые запросы.
Что именно я увижу в этой панели?Запросы к базе данных с привязками и временем выполнения, текущий маршрут, загруженные view, события, обращения к кэшу, записи логов, отправленную почту, исключения, расход памяти и тайминги приложения — плюс версию и окружение Laravel. Редиректы и запросы Ajax/Livewire показываются в выпадающем списке.
Могу ли я писать в панель свои сообщения или замерять, сколько что-то выполняется?Да: фасад Debugbar принимает сообщения с уровнями PSR-3, позволяет запускать и останавливать замеры времени и логировать исключения, а для частых вызовов есть функции-помощники. Свои собственные DataCollectors можно зарегистрировать через контейнер или тот же фасад.
Работает ли это с Laravel Octane?Да, Laravel Debugbar 4.x работает с Octane сразу, без настройки. При обновлении с 3.x нужно только удалить запись 'flush' для debugbar в файле config/octane.php.
Почему теперь пакет называется fruitcake/laravel-debugbar?Пакет переименовали с barryvdh/laravel-debugbar в fruitcake/laravel-debugbar. В README сказано, что существующим пользователям можно спокойно перейти: удалить старый пакет командой composer remove --dev и установить пакет с новым именем.
Creator
fruitcake
Size
15.4 MB
Stars
19.3K
Age
13y
Commits · 90 Days