tool-debugger.md 6.38 KB
Newer Older
1 2 3
Debug toolbar and debugger
==========================

4
> Note: This section is under development.
Qiang Xue committed
5

Larry Ullman committed
6 7
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).
8

Larry Ullman committed
9
Out of the box these tools allow you to:
10

Larry Ullman committed
11 12 13 14 15 16 17 18
- 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
19

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

22

23 24 25
Installing and configuring
--------------------------

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

Qiang Xue committed
28
```php
29
'bootstrap' => ['debug'],
30
'modules' => [
MetalGuardian committed
31
    'debug' => 'yii\debug\Module',
32
]
docsolver committed
33 34
```

35 36
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:
37

Qiang Xue committed
38
```php
39
'bootstrap' => ['debug'],
40
'modules' => [
41 42 43 44
    'debug' => [
        'class' => 'yii\debug\Module',
        'allowedIPs' => ['1.2.3.4', '127.0.0.1', '::1']
    ]
45 46
]
```
47

48 49 50 51
If you are using `enableStrictParsing` URL manager option, add the following to your `rules`:

```php
'urlManager' => [
52 53 54 55 56
    'enableStrictParsing' => true,
    'rules' => [
        // ...
        'debug/<controller>/<action>' => 'debug/<controller>/<action>',
    ],
57 58 59
],
```

60 61 62 63 64
> Note: the debugger stores information about each request in the `@runtime/debug` directory. If you have problems using
> The debugger such as weird error messages when using it or the toolbar not showing up or not showing any requests, check
> whether the web server has enough permissions to access this directory and the files located inside.


Larry Ullman committed
65
### Extra configuration for logging and profiling
66

Larry Ullman committed
67 68
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.
69

Larry Ullman committed
70 71
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.
72

Larry Ullman committed
73 74 75 76
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:
77 78 79

```php
return [
80 81 82 83
    // ...
    'components' => [
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0, // <-- here
84 85
```

Larry Ullman committed
86
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:
87

88
```php
89
defined('YII_DEBUG') or define('YII_DEBUG', true);
90 91
```

Larry Ullman committed
92
> 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
93

94

95 96 97
Creating your own panels
------------------------

Larry Ullman committed
98 99 100 101 102 103 104 105
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.
106

Larry Ullman committed
107
First we need to implement the `Panel` class in `panels/ViewsPanel.php`:
108 109 110 111 112 113 114 115 116 117 118 119 120

```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
{
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 155 156 157 158 159 160 161 162 163 164
    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;
    }
165 166 167
}
```

Larry Ullman committed
168
The workflow for the code above is:
169

Larry Ullman committed
170 171 172 173 174
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
175 176
   `getDetail` for the same purpose.

Larry Ullman committed
177
Now it's time to tell the debugger to use the new panel. In `config/web.php`, the debug configuration is modified to:
178 179 180

```php
if (YII_ENV_DEV) {
181
    // configuration adjustments for 'dev' environment
182
    $config['bootstrap'][] = 'debug';
183 184 185 186 187 188
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
        'panels' => [
            'views' => ['class' => 'app\panels\ViewsPanel'],
        ],
    ];
189 190 191 192 193

// ...
```

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