module-debug.md 6 KB
Newer Older
1 2 3
Debug toolbar and debugger
==========================

Larry Ullman committed
4 5
Yii2 includes a handy toolbar, and built-in debugger, for faster development and debugging of your applications. The toolbar displays information
about the currently opened page, while the debugger can be used to analyze data you've previously collected (i.e., to confirm the values of variables).
6

Larry Ullman committed
7
Out of the box these tools allow you to:
8

Larry Ullman committed
9 10 11 12 13 14 15 16
- Quickly get the framework version, PHP version, response status, current controller and action, performance info and
  more via toolbar
- Browse the application and PHP configuration
- View the request data, request and response headers, session data, and environment variables
- See, search, and filter the logs
- View any profiling results
- View the database queries executed by the page
- View the emails sent by the application
17

Larry Ullman committed
18
All of this information will be available per request, allowing you to revisit the information for past requests as well.
19

20 21 22
Installing and configuring
--------------------------

Larry Ullman committed
23
To enable these features, add these lines to your configuration file to enable the debug module:
docsolver committed
24

Qiang Xue committed
25
```php
26
'bootstrap' => ['debug'],
27
'modules' => [
MetalGuardian committed
28
    'debug' => 'yii\debug\Module',
29
]
docsolver committed
30 31
```

Larry Ullman committed
32
By default, the debug module only works when browsing the website from localhost. If you want to use it on a remote (staging) server, add the parameter `allowedIPs` to the configuration to whitelist your IP:
33

Qiang Xue committed
34
```php
35
'bootstrap' => ['debug'],
36
'modules' => [
37 38 39 40
    'debug' => [
        'class' => 'yii\debug\Module',
        'allowedIPs' => ['1.2.3.4', '127.0.0.1', '::1']
    ]
41 42
]
```
43

44 45 46 47
If you are using `enableStrictParsing` URL manager option, add the following to your `rules`:

```php
'urlManager' => [
48 49 50 51 52
    'enableStrictParsing' => true,
    'rules' => [
        // ...
        'debug/<controller>/<action>' => 'debug/<controller>/<action>',
    ],
53 54 55
],
```

Larry Ullman committed
56
### Extra configuration for logging and profiling
57

Larry Ullman committed
58 59
Logging and profiling are simple but powerful tools that may help you to understand the execution flow of both the
framework and the application. These tools are useful for development and production environments alike.
60

Larry Ullman committed
61 62
While in a production environment, you should log only significantly important  messages manually, as described in
[logging guide section](logging.md). It hurts performance too much to continue to log all messages in production.
63

Larry Ullman committed
64 65 66 67
In a development environment, the more logging the better, and it's especially useful to record the execution trace.

In order to see the trace messages that will help you to understand what happens under the hood of the framework, you need to set the
trace level in the configuration file:
68 69 70

```php
return [
71 72 73 74
    // ...
    'components' => [
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0, // <-- here
75 76
```

Larry Ullman committed
77
By default, the trace level is automatically set to `3` if Yii is running in debug mode, as determined by the presence of the following line in your `index.php` file:
78

79
```php
80
defined('YII_DEBUG') or define('YII_DEBUG', true);
81 82
```

Larry Ullman committed
83
> Note: Make sure to disable debug mode in production environments since it may have a significant and adverse performance effect. Further, the debug mode may expose sensitive information to end users.
docsolver committed
84

85 86 87
Creating your own panels
------------------------

Larry Ullman committed
88 89 90 91 92 93 94 95
Both the toolbar and debugger are highly configurable and customizable. To do so, you can create your own panels that collect
and display the specific data you want. Below we'll describe the process of creating a simple custom panel that:

- Collects the views rendered during a request
- Shows the number of views rendered in the toolbar
- Allows you to check the view names in the debugger

The assumption is that you're using the basic application template.
96

Larry Ullman committed
97
First we need to implement the `Panel` class in `panels/ViewsPanel.php`:
98 99 100 101 102 103 104 105 106 107 108 109 110

```php
<?php
namespace app\panels;

use yii\base\Event;
use yii\base\View;
use yii\base\ViewEvent;
use yii\debug\Panel;


class ViewsPanel extends Panel
{
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
    private $_viewFiles = [];

    public function init()
    {
        parent::init();
        Event::on(View::className(), View::EVENT_BEFORE_RENDER, function (ViewEvent $event) {
            $this->_viewFiles[] = $event->sender->getViewFile();
        });
    }


    /**
     * @inheritdoc
     */
    public function getName()
    {
        return 'Views';
    }

    /**
     * @inheritdoc
     */
    public function getSummary()
    {
        $url = $this->getUrl();
        $count = count($this->data);
        return "<div class=\"yii-debug-toolbar-block\"><a href=\"$url\">Views <span class=\"label\">$count</span></a></div>";
    }

    /**
     * @inheritdoc
     */
    public function getDetail()
    {
        return '<ol><li>' . implode('<li>', $this->data) . '</ol>';
    }

    /**
     * @inheritdoc
     */
    public function save()
    {
        return $this->_viewFiles;
    }
155 156 157
}
```

Larry Ullman committed
158
The workflow for the code above is:
159

Larry Ullman committed
160 161 162 163 164
1. `init` is executed before any controller action is run. This method is the best place to attach handlers that will collect data during the controller action's execution.
2. `save` is called after controller action is executed. The data returned by this method will be stored in a data file. If nothing is returned by this method, the panel
   won't be rendered.
3. The data from the data file is loaded into `$this->data`. For the toolbar, this will always represent the latest data, For the debugger, this property may be set to be read from any previous data file as well.
4. The toolbar takes its contents from `getSummary`. There, we're showing the number of view files rendered. The debugger uses
165 166
   `getDetail` for the same purpose.

Larry Ullman committed
167
Now it's time to tell the debugger to use the new panel. In `config/web.php`, the debug configuration is modified to:
168 169 170

```php
if (YII_ENV_DEV) {
171
    // configuration adjustments for 'dev' environment
172
    $config['bootstrap'][] = 'debug';
173 174 175 176 177 178
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
        'panels' => [
            'views' => ['class' => 'app\panels\ViewsPanel'],
        ],
    ];
179 180 181 182 183

// ...
```

That's it. Now we have another useful panel without writing much code.