Giter Site home page Giter Site logo

yii2-debug's Introduction

yii2-debug

Debug panel for Yii 1.1 (ported from Yii 2).

Latest Stable Version Total Downloads

Installation

This extension is available at packagist.org and can be installed via composer by following command:

composer require --dev zhuravljov/yii2-debug.

If you want to install this extension manually just copy sources to /protected/extensions directory.

To enable toolbar in your application add following lines to config:

return array(
    'preload' => array(
        'debug',
    ),
    'components' => array(
        'debug' => array(
            'class' => 'vendor.zhuravljov.yii2-debug.Yii2Debug', // composer installation
            //'class' => 'ext.yii2-debug.Yii2Debug', // manual installation
        ),
        'db' => array(
            'enableProfiling' => true,
            'enableParamLogging' => true,
        ),
    ),
);

Configuration

You can customize debug panel behavior with this options:

  • enabled - enable/disable debug panel.
  • allowedIPs - list of IPs that are allowed to access debug toolbar. Default array('127.0.0.1', '::1').
  • accessExpression - additional php expression for access evaluation.
  • logPath - directory storing the debugger data files. This can be specified using a path alias. Default /runtime/debug.
  • historySize - maximum number of debug data files to keep. If there are more files generated, the oldest ones will be removed.
  • highlightCode - highlight code. Highlight SQL queries and PHP variables. This parameter can be set for each panel individually.
  • moduleId - module ID for viewing stored debug logs. Default debug.
  • showConfig - show brief application configuration page. Default false.
  • hiddenConfigOptions - list of unsecure component options to hide (like login, passwords, secret keys). Default is to hide username and password of db component.
  • internalUrls - use nice routes rules in debug module.
  • panels - list of debug panels.

Each attached panel can be configured individually, for example:

'debug' => array(
    'class' => 'ext.yii2-debug.Yii2Debug',
    'panels' => array(
        'db' => array(
            // Disable code highlighting.
            'highlightCode' => false,
            // Disable substitution of placeholders with values in SQL queries.
            'insertParamValues' => false,
        ),
    ),
),

Each panel have callback option filterData. You can define custom function for filtering input data before writing it in to debug log. It's useful when you need to hide something secret or just delete data from logs. Be careful with data structure manipulation. It can lead to log parsing errors.

Example:

'debug' => array(
    'class' => 'ext.yii2-debug.Yii2Debug',
    'panels' => array(
        'db' => array(
            'filterData' => function($data){
                // Your code here
                return $data;
            }
        ),
    ),
),

Creating own panels

To create own debug panel you can extend class Yii2DebugPanel, for example:

class MyTestPanel extends Yii2DebugPanel
{
    /**
     * The name of panel printed in debugger
     */
    public function getName()
    {
        return 'Name';
    }

    /**
     * Return summary html with results of execution in current request.
     * Data is available through $this->data
     */
    public function getSummary()
    {
        return '';
    }

    /**
     * Return detailed html report with results of execution in current request.
     * Data is available through $this->data
     */
    public function getDetail()
    {
        return '';
    }

    /**
     * Return data required for storing in logs.
     */
    public function save()
    {
        return array();
    }
}

And attach this panel in config:

'panels' => array(
    'test' => array(
        'class' => 'path.to.panel.MyTestPanel',
        // ...
    ),
),

Disable individual panels

To disable an individual panel, either a core or custom panel, set the enabled property in the panel config to false.

Example: Disable core profiling panel

'panels' => array(
    'profiling' => array(
        'enabled' => false,
        // ...
    ),
),

Variables dumping

With static method Yii2Debug::dump() you can dump any data and examine it later in debug log.

Miscellaneous

Status Code

If you using PHP < 5.4, debug panel can't detect redirects by himself. You can use following code as workaround:

'panels' => array(
    'request' => array(
        'filterData' => function($data){
            if (empty($data['statusCode'])) {
                if (isset($data['responseHeaders']['Location'])) {
                    $data['statusCode'] = 302;
                } else {
                    $data['statusCode'] = 200;
                }
            }
            return $data;
        },
    ),
),

Such code just set 302 code if Location header is present. Codes like 4xx and 5xx can be detected in debug panel by himself. In PHP 5.4 and higher debug panel uses native php function http_response_code() for detecting http response code, and there is no need to use this workaround.

yii2-debug's People

Contributors

bashkarev avatar bkonetzny avatar chuprik avatar evgen-d avatar kikimor avatar zhuravljov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-debug's Issues

SQL execute

Добавить возможность выполнять сохраненные SELECT-запросы и просматривать результаты.

Сделать после #24.

Не грузится jQuery, если отключен в конфиге Yii

Если в конфиге Yii отключен дефолтный jQuery - не отрабаывается зависимость в этом коде

Yii::app()->getClientScript()
    ->addPackage('yii2-debug', array(
        'baseUrl' => CHtml::asset(Yii::getPathOfAlias('yii2-debug.assets')),
        'js' => array(
            YII_DEBUG ? 'js/bootstrap.js' : 'js/bootstrap.min.js',
            'js/filter.js',
        ),
        'css' => array(
            YII_DEBUG ? 'css/bootstrap.css' : 'css/bootstrap.min.css',
            'css/main.css',
        ),
        'depends' => array('jquery'),
    ))
    ->registerPackage('yii2-debug');

и не загружется jQuery, соответственно не работают некоторые скрипты (табы и т.п.)

Yii2DbPanel::getConnectionsInfo() error

Есть такой метод Yii2DbPanel::getConnectionsInfo(), а в нем код

if (isset($connection['info'])) {
                foreach (explode('  ', $connection['info']) as $line) {
                    list($key, $value) = explode(': ', $line, 2);
                    $connection[$key] = $value;
                }
                unset($connection['info']);
            }

Что делает этот код? и что делать тем у кого там лежит текст не имеющий двойных пробелов и двоеточий?

Проблема такая, что невозможно посмотреть панель БД. Вываливается с ошибкой.

Выводить полный конфиг

Было бы здорово, если бы была возможность смотреть весь конфиг yii. То что сейчас выводится в блоке "Application Configuration" как-то совсем скудно.

кешированный SQL-запрос или нет?

Есть ли возможность просматривать кол-во кэшированных SQL запросов?
Общее кол-во(время выполнение)/кол-во в кеше(время выполнения) ?
Подсветка кэшированного запроса SQL в "Database"

Unable to see SQL queries

The database panel is always empty for me. I'm able to see data Logs panel. I'm sure I have enabled both debugging, trace level & db params to true, still that panel is empty. Any idea?

Поддержка php 5.2

Было бы здорово, если бы у debug-панели были минимальные требования как и у первого yii. В частности поддержка php 5.2. Так-то вроде бы уже везде стоит 5.3, но вот столкнулись с ситуацией что стоит php 5.2, а запустить панельку не удается.

Сделать открытите дебаггера как popup-окно

Можно сделать, чтобы при нажатии на панель она разворачивалась на высоту всего экрана, а затем при событии сворачивалась обратно. Не удобно каждый раз перезагружать страницу. Спасибо.

Yii2ViewPanel

Панель с информацией по отрендереным вьювам.

получение ip изменить

в yii2Debug в checkAccess
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1';
заменить на Yii::app()->request->userHostAddress
как это сделано в gii

так как ip с nginx может быть не совсем таким как его хотелось бы

Ошибка в unit тестах

При запуске unit тестов модуль пытается создать asset в папке Temp:

Fatal error: Uncaught exception 'CException' with message 'Путь CAssetManager.basePath "C:\Users\������\AppData\Local\Temp\assets" задан неверно. Удостоверьтесь, что директория существует и доступна для записи пользователю, под которым запущен веб-сервер.' in D:\WebServers\home\cross-auth.lan\www\framework\web\CAssetManager.php:138

Stack trace:

#0 D:\WebServers\home\cross-auth.lan\www\framework\web\CAssetManager.php(123): CAssetManager->setBasePath('C:\Users\??????...')
#1 D:\WebServers\home\cross-auth.lan\www\framework\web\CAssetManager.php(217): CAssetManager->getBasePath()
#2 D:\WebServers\home\cross-auth.lan\www\framework\web\helpers\CHtml.php(1295): CAssetManager->publish('D:\WebServers\h...', false)
#3 D:\WebServers\home\cross-auth.lan\www\protected\extensions\yii2-debug\Yii2Debug.php(161): CHtml::asset('D:\WebServers\h...')
#4 D:\WebServers\home\cross-auth.lan\www\protected\extensions\yii2-debug\Yii2Debug.ph in D:\WebServers\home\cross-auth.lan\www\framework\web\CAssetManager.php on line 138

Ошибка после установки

После установки расширения не могу заставить его нормально работать. Конфигурацию прописал как в мануале.

В итоге есть ошибка в консоли

/debug/default/toolbar/tag/5228832de1b9e 404 (Not Found)

Полагаю дело в роутах, но как исправить непонятно...

Module config merging bug

Yii Debug.php, line 95. Modules configs was merged few times.

Yii::app()->setModules([
    $this->moduleId => array(
        'class' => 'Yii2DebugModule',
        'component' => $this,
    ),
]);

Ограничение логирования по IP

Кейс использования дебагера такой - для оптимизации нужно профилировать страницы и запросы на продакшен серверах, именно с продакшен базой. Но при включении дебагера лог пишет все события всех пользователей и раздувается до невероятных размеров.

Поэтому необходимо иметь возможность писать лог и показывать тулбар только при работе с определенных IP.

Предложение добавить параметр logAllowedIPsOnly (по умолчанию = false)

Возможность удалять лог

Собственно на странице просмотра списка "логов" дебагера, добавить кнопку явного удаления лога, или массового удаления логов,

Oracle query explain does not work

Oracle query explain plan does not work.
For fetching execution plan at first need to execute (not fetch)
EXPLAIN PLAN FOR ' . $query
After that plan will be stored in dbms_xplan.display table, you can fetch it and show.


Текущая структура класса не позволяет так просто разместить два запроса.
Нужен редизайн класса для внедрения такого функционала или костыль :)

Пустая вкладка Database

в конфигах прописал
'enableProfiling' => true,
'enableParamLogging' => true,
но при открытии вкладки database она пустует.

composer

Прекрасная библиотека, спасибо!
Ну и composer напрашивается сам собой :)

htmlspecialchars

Собственно появилась одна очень интересная строка в дебагере.
( http://www.screencapture.ru/uploaded/4a/fc/47/4AFC479c.jpg )
2013-12-18 07:59:32 69.199.140.194 Guest �W���
Guest - это я для удобства у себя вывел имя пользователя. Так же немного поправил код для привязке не к ИПу а к пользователю, если нужно поделюсь.
Но вот при попытке посмотреть что там было - вылетает 500 ошибка и плывет дизайн.
Вот собственно как это происходит: http://www.screencapture.ru/file/149B814e
После попытка зайти в тот раздел - не могу зайти вообще в никакой. Хотя как то эта проблема решается.
Если пойму как решать - отпишусь)

Lock and unlock of deleting some logs

Актуально когда расширение используется на корпоративном тестовом сервере, и разработчикам необходимо делиться ссылками на explain некоторых sql-запросов. Без такой блокировки, к моменту когда ссылка будет открыта, лог может быть удален по ограничению Yii2Debug::$historySize.

Если explain запроса открыт в отдельной вкладке блокировку лога нужно устанавливать автоматически.

То же самое относится и к результатам выполнения запросов из #21.

Unable to deactivate core panel

From Yii2Debug for public $panels = array();

You may also disable a core panel by setting it to be false in this property.

I tried to disable the config panel by using the following config:

'panels' => array(
  'config' => false,
),

I then get the following error which comes from Yii2Debug L#100:

Object configuration must be an array containing a "class" element.

I see no place where panels with the value false are filtered out, is there anything I'm missing?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.