Debugging, in computer programming and engineering, is a multistep process that involves identifying a problem, isolating the source of the problem, and then either correcting the problem or determining a way to work around it. The final step of debugging is to test the correction or workaround and make sure it works.

There are built in debuging features in Magento 2 like logging, xdebug support, profiler, developer mode and enable template patch hints.

In this article we will discuss both debugging tricks and tools.

Enable or Disable Maintenance Mode

Magento uses maintenance mode to disable bootstrapping. It is recommended to put website on maintenance mode while you’re maintaining, upgrading, or re-configuring your site.

Just we need to add a new blank file “.maintenance.flag” under var/ directory site will automatically goes in maintenance mode.

var/.maintenance.flag

Once maintenance flag is enabled, site will display like below message:

“Service Temporarily Unavailable
The server is temporarily unable to service your request due to maintenance downtime or
capacity problems. Please try again later.”

Magento2 Error Reporting

Magento2 comes with 3 different modes,

  1. Default
  2. Developer
  3. Production

By default, Magento runs under “default” mode and that’s why we don’t get the error log at the front-end of the site. It need to be set on Developer mode to generate error log. You need to rename file local.xml.sample to local.xml under pub/errors.

Full details can be found at:
http://devdocs.magento.com/guides/v2.2/config-guide/bootstrap/magento-modes.html

Magento2 Sql Log And Stack

Many of the cases we need to log MySQL queries and stack to debug and find the solution. As Magento2 does not provide a default configuration from admin to enable MySQL log, we need to do code changes in Magento2 di.xml file.

The file can be located to root/app/etc/di.xml. There are few changes which need to be done in this file.

1. Change “Quite” to “File”:

Find word “Quiet” and replace with “File”.

Line before change:

<preference for=”Magento\Framework\DB\LoggerInterface” type=”Magento\Framework\DB\Logger\Quiet“/>

After change

<preference for=”Magento\Framework\DB\LoggerInterface” type=”Magento\Framework\DB\Logger\File“/>

2. Add below code at the end of file but before </config> tag:

<type name=”Magento\Framework\DB\Logger\File”>
<arguments>
<argument name=”logAllQueries” xsi:type=”boolean”>true</argument>
<argument name=”debugFile” xsi:type=”string”>debug/query.log</argument>
<argument name=”logQueryTime” xsi:type=”decimal”>0.50</argument>
<argument name=”logCallStack” xsi:type=”boolean”>true</argument>
</arguments>
</type>

3. Clean cache

Magento 2 Function Stack

Function stack trick to print function stack within program one or more time help to track and reach the solution.
We need to use below class after namespace line within our class.

Use Magento\Framework\Debug;
After this add following code for back trace stack
print_r(Debug::backtrace(true, true));

We can also log back trace in log file; to log back track in file use below code:
$this _logger info(‘Any String’, [‘data:’=>Debug::backtrace(t → → rue, true)]);

Magento2 Functional Log

We can apply log with the code through the following tricks
1. $context->getLogger();
We need to create a logger class within our module like below, Here one“HelloWorld“
module is created by oscprofessionals team.
namespace Oscprofessionals\HelloWorld\Logger;
class Logger extends \Magento\Framework\View\Element\Template
{
protected $_customLogger;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Psr\Log\LoggerInterface $customLogger
) {
$this->_customLogger = $customLogger;
parent::__construct($context);
}
public function execute()
{
// log location: var/log/debug.log
$this->_customLogger->addDebug($message);
Output
[2017-11-15 15:40:41] main.DEBUG:
// log location: var/log/system.log
$this->_customLogger->addInfo($message);
Output
[2017-11-15 15:40:41] main.INFO: Message
// log location: var/log/system.log
$this->_customLogger->addNotice($message);
Output
[2017-11-15 15:40:41] main.NOTICE:
// log location: var/log/system.log
$this->_customLogger->addError($message);
Output
[2017-11-15 15:40:41] main.ERROR:
// log location: var/log/system.log
$this->_customLogger->critical($e);
Output
[2017-11-15 15:40:41] main.CRITICAL:
}
}
2. We can also write to the logs using the zend library within the program.
$writer = new \Zend\Log\Writer\Stream(BP . ‘/var/log/log_file_name.log’);
$this->_logger = new \Zend\Log\Logger();
$this->_logger->addWriter($writer);
// String
$this->_logger->info(‘Your text message’);
// Array
$this _logger info(‘Any String’, [‘data:’=>$array]);

Magento2 Enable PHP Display Errors

Magento2 giving the option to Enable / Disable PHP errors on site. We need to change in following file.
app/bootstrap.php
From
#ini_set(‘display_errors’,’1′);
To
ini_set(‘display_errors’,’1′);

Magento2 Path Hints For Admin and Frontend

In Magento 1, there was an option to Enable or Diable Path hints from admin configuration.
MyProject ->admin-> Stores-> Configuration-> Advanced ->Developer
Same option is available in same configuration place in Magento2 with additional feature for
Enable or Disable Path hint for Admin

Debug Tab:

1. Enabled Template Path Hints for Storefront

2. Enabled Template Path Hints for Admin (New in Magento2)
3. Add Block Names to Hints

Debug Tools

Some useful modules are freely available for debugging.
1. Mgt Developer Toolbar

https://www.mgt-commerce.com/documentation/magento2-mgt-developer-toolbar

https://github.com/mgtcommerce/Mgt_Developertoolbar

Download and Install

 

The toolbar shows you all important information for performance optimization and Magento
development.
Main Features
  • Profiler
  • Memory Consumption
  • List of all Database Queries
  • Block nesting
  • Cache Storage Information
  • Session Storage Information
  • Enabled / Disabled Modules
  • Request / Response Data
  • Handles
  • Events / Observers
  • Plugins
  • Preferences
  • PHP-Info

2. Quickdevbar

 

https://github.com/vpietri/magento2-developer-quickdevbar
Download and Install
The structure of this toolbar is extremely simple you just need to add a new block in the
layout to get your tab running.
The toolbar is displayed by default if your web server is on your local development
environment.
Features
  • Info: Main information about controller, route, action and store. Search on core config data. Dedicated tab output for local and global phpinfo.
  • Design: List handles called and display layout structure of nested blocks and containers
  • Profile: View current observers, all events dispatched, collections and models loaded, plugins instantiated
  • Queries: Statistics about executed queries and detailed query listing with syntax highlighting of main SQL keywords
  • Logs: Display log files with ability to reset these files
  • Actions : Easily toggle template hints and inline translation and flush cache
  • Help: Show module version and link to github