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

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

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
Installing and configuring
--------------------------

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

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

Larry Ullman committed
34
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:
35

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

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

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

Larry Ullman committed
58
### Extra configuration for logging and profiling
59

Larry Ullman committed
60 61
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.
62

Larry Ullman committed
63 64
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.
65

Larry Ullman committed
66 67 68 69
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:
70 71 72

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

Larry Ullman committed
79
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:
80

81
```php
82
defined('YII_DEBUG') or define('YII_DEBUG', true);
83 84
```

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

87 88 89
Creating your own panels
------------------------

Larry Ullman committed
90 91 92 93 94 95 96 97
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.
98

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

```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
{
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 155 156
    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;
    }
157 158 159
}
```

Larry Ullman committed
160
The workflow for the code above is:
161

Larry Ullman committed
162 163 164 165 166
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
167 168
   `getDetail` for the same purpose.

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

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

// ...
```

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