调试工具栏和调试器

未匹配的标注

调试工具栏和调试器

This extension provides a debugger for Yii 2 applications. When this extension is used, a debugger toolbar will appear at the bottom of every page. The extension also provides a set of standalone pages to display more detailed debug information.

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).

Out of the box these tools allow you to:

  • 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.

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

安装

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist yiisoft/yii2-debug

or add

"yiisoft/yii2-debug": "~2.0.0"

to the require section of your composer.json file.

配置应用

To enable extension, add these lines to your configuration file to enable the debug module:

'bootstrap' => ['debug'],
'modules' => [
    'debug' => [
        'class' => 'yii\debug\Module',
    ],
]

You will see a debugger toolbar showing at the bottom of every page of your application. You can click on the toolbar to see more detailed debug information.

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:

'bootstrap' => ['debug'],
'modules' => [
    'debug' => [
        'class' => 'yii\debug\Module',
        'allowedIPs' => ['1.2.3.4', '127.0.0.1', '::1']
    ]
]

If you are using enableStrictParsing URL manager option, add the following to your rules:

'urlManager' => [
    'enableStrictParsing' => true,
    'rules' => [
        // ...
        'debug/<controller>/<action>' => 'debug/<controller>/<action>',
    ],
],

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.

日志和分析的额外配置

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.

While in a production environment, you should log only significantly important messages manually, as described in logging guide section. It hurts performance too much to continue to log all messages in production.

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:

return [
    // ...
    'components' => [
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0, // <-- here

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:

defined('YII_DEBUG') or define('YII_DEBUG', true);

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.

配置数据库面板

Database panel default sorting and filtering can be configured like the following:

$config['modules']['debug'] = [
    'class' => 'yii\debug\Module',
    'panels' => [
        'db' => [
            'class' => 'yii\debug\panels\DbPanel',
            'defaultOrder' => [
                'seq' => SORT_ASC
            ],
            'defaultFilter' => [
                'type' => 'SELECT'
            ]
        ],
    ],
];

在IDE中打开的额外配置

Wouldn’t it be nice to be able to open files directly from the debug trace?

Well, you can! With a few settings you’re ready to go!

You can create a link to open files in your favorite IDE with this configuration:

return [
    'bootstrap' => ['debug'],
    'modules' => [
        'debug' => [
            'class' => 'yii\debug\Module',
            'traceLine' => '<a href="phpstorm://open?url={file}&line={line}">{file}:{line}</a>',
            // uncomment and adjust the following to add your IP if you are not connecting from localhost.
            //'allowedIPs' => ['127.0.0.1', '::1'],
        ],
        // ...
    ],
    ...
];

You must make some changes to your OS. See these examples:

Windows

1) Create a WScript file open_phpstorm.js:

Create a file C:\Program Files (x86)\JetBrains\open_phpstorm.js (example for PhpStorm) with the following content:

var settings = {
    // Set to 'true' (without quotes) if run on Windows 64bit. Set to 'false' (without quotes) otherwise.
    x64: true,

    // Set to folder name, where PhpStorm was installed to (e.g. 'PhpStorm')
    folder_name: 'PhpStorm 2016.2.1',

    // Set to window title (only text after dash sign), that you see, when switching to running PhpStorm instance
    window_title: 'PhpStorm 2016.2.1',

    // In case your file is mapped via a network share and paths do not match.
    // eg. /var/www will can replaced with Y:/
    projects_basepath: '',
    projects_path_alias: ''
};

// don't change anything below this line, unless you know what you're doing
var    url = WScript.Arguments(0),
    match = /^ide:\/\/(?:.+)file:\/\/(.+)&line=(\d+)$/.exec(url),
    project = '',
    editor = '"C:\\' + (settings.x64 ? 'Program Files' : 'Program Files (x86)') + '\\JetBrains\\' + settings.folder_name + '\\bin\\PhpStorm.exe"';

if (match) {

    var    shell = new ActiveXObject('WScript.Shell'),
        file_system = new ActiveXObject('Scripting.FileSystemObject'),
        file = decodeURIComponent(match[1]).replace(/\+/g, ' '),
        search_path = file.replace(/\//g, '\\');

    if (settings.projects_basepath != '' && settings.projects_path_alias != '') {
        file = file.replace(new RegExp('^' + settings.projects_basepath), settings.projects_path_alias);
    }

    while (search_path.lastIndexOf('\\') != -1) {
        search_path = search_path.substring(0, search_path.lastIndexOf('\\'));

        if(file_system.FileExists(search_path+'\\.idea\\.name')) {
            project = search_path;
            break;
        }
    }

    if (project != '') {
        editor += ' "%project%"';
    }

    editor += ' --line %line% "%file%"';

    var command = editor.replace(/%line%/g, match[2])
                        .replace(/%file%/g, file)
                        .replace(/%project%/g, project)
                        .replace(/\//g, '\\');

    shell.Exec(command);
    shell.AppActivate(settings.window_title);
}
2) Create a registry file and execute this file

Create a registry file C:\Program Files (x86)\JetBrains\open_phpstorm.reg (example for PhpStorm) with the following content and make sure the paths are correct:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\ide]
@="\"URL:ide Protocol\""
"URL Protocol"=""

[HKEY_CLASSES_ROOT\ide\shell\open\command]
@="wscript \"C:\\Program Files (x86)\\JetBrains\\open_phpstorm.js\" %1"

Now you are able to use the ide:// protocol in your browser.

When you click such a link, the IDE will automatically open the file and move the cursor to the corresponding line.

Disable links

IDE links for traces are created by default. You have to set the property yii\debug\Module::traceLink to false to render a textual line only.

<?php

...
'modules' => [
    'debug' => [
        'class' => 'yii\debug\Module',
        'traceLink' => false
    ]
]

...

Virtualized or dockerized

If your application is run under a virtualized or dockerized environment, it is often the case that the application’s base path is different inside of the virtual machine or container than on your host machine. For the links work in those situations, you can configure tracePathMappings like this (change the path to your app):

'tracePathMappings' => [
    '/app' => '/path/to/your/app',
],

Or you can create a callback for traceLine for even more control:

'traceLine' => function($options, $panel) {
    $filePath = $options['file'];
    if (StringHelper::startsWith($filePath, Yii::$app->basePath)) {
        $filePath = '~/path/to/your/app' . substr($filePath, strlen(Yii::$app->basePath));
    }
    return strtr('<a href="ide://open?url=file://{file}&line={line}">{text}</a>', ['{file}' => $filePath]);
},

切换用户

You can use log in as any user and reset to back to your primary user. In order to enable the feature you need to configure access permissions in the UserPanel config. By default access is denied to everyone.

return [
    'bootstrap' => ['debug'],
    'modules' => [
        'debug' => [
            'class' => 'yii\debug\Module',
            'panels' => [
                'user' => [
                    'class'=>'yii\debug\panels\UserPanel',
                    'ruleUserSwitch' => [
                        'allow' => true,
                        'roles' => ['manager'],
                    ]
                ]
            ]
        ],
        // ...
    ],
    ...
];

For details see Guide Authorization.

Skipping URLs from being displayed in toolbar

In some cases, such as AJAX-polling, toolbar is getting spammed quickly and becomes unusable. There is a way to ignore these URLs for such cases:

return [
    'bootstrap' => ['debug'],
    'modules' => [
        'debug' => [
            'class' => 'yii\debug\Module',
            'skipAjaxRequestUrl' => [
                'notification/status'
            ],
        ],
        // ...
    ],
    ...
];

自定义面板

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 project template.

First we need to implement the Panel class in panels/ViewsPanel.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
{
    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=\"yii-debug-toolbar__label yii-debug-toolbar__label_info\">$count</span></a></div>";
    }

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

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

The workflow for the code above is:

  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 getDetail for the same purpose.

Now it’s time to tell the debugger to use the new panel. In config/web.php, the debug configuration is modified to:

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
        'panels' => [
            'views' => ['class' => 'app\panels\ViewsPanel'],
        ],
    ];

// ...

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

Advanced options

Allow ‘click’ events in your toolbar summary block

By default an inline preview is shown when clicking on the summary on the toolbar. To override this behavior add the yii-debug-toolbar__block_ignore_click class to your root <div> in getSummary().

Events

If you need client side programmatic access to the toolbar, for example to bind JavaScript events, you can listen to the yii.debug.toolbar_attached event on the document. For example:

document.addEventListener('yii.debug.toolbar_attached', function(event) {
    var toolbar = event.target;
}

💖喜欢本文档的,欢迎点赞、收藏、留言或转发,谢谢支持!
作者邮箱:zhuzixian520@126.com,github地址:github.com/zhuzixian520

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
zhuzixian520
讨论数量: 0
发起讨论 只看当前版本


暂无话题~