To print debug traces in Magento 2 for checking error details, you can follow these steps:
- Enable Developer Mode: Ensure that your Magento 2 installation is in developer mode. Developer mode provides more detailed error messages and is easier to debug.
bin/magento deploy:mode:set developer
- Enable Logging: Magento 2 uses Monolog for logging. Ensure that logging is enabled in your
app/etc/env.phpfile by setting'log' => ['level' => 'debug']. - Using the Logger: You can use Magento’s built-in logging functionality to log messages to
var/log/system.logor create a custom log file.- Log to
system.log:
<?php namespace Vendor\Module\Controller\Index; use Psr\Log\LoggerInterface; class Index extends \Magento\Framework\App\Action\Action { protected $logger; public function __construct( \Magento\Framework\App\Action\Context $context, LoggerInterface $logger ) { $this->logger = $logger; parent::__construct($context); } public function execute() { $this->logger->debug('Debug message'); $this->logger->debug(print_r($someVariable, true)); // For printing array or object // Your code here } } - Log to a custom file:
<?php namespace Vendor\Module\Controller\Index; use Magento\Framework\Logger\Monolog; class Index extends \Magento\Framework\App\Action\Action { protected $customLogger; public function __construct( \Magento\Framework\App\Action\Context $context, Monolog $customLogger ) { $this->customLogger = $customLogger; parent::__construct($context); } public function execute() { $this->customLogger->addDebug('Debug message', ['source' => 'CustomLog']); $this->customLogger->addDebug(print_r($someVariable, true), ['source' => 'CustomLog']); // Your code here } }
- Log to
- Using PHP’s
debug_backtrace(): If you want to print a debug trace to understand the flow, you can use PHP’s built-indebug_backtrace()function.<?php $debugTrace = debug_backtrace(); $this->logger->debug(print_r($debugTrace, true));
- Error Handling: To catch and log exceptions, you can use try-catch blocks and log the exception details.
<?php try { // Your code here } catch (\Exception $e) { $this->logger->error('Error: ' . $e->getMessage()); $this->logger->error('Trace: ' . $e->getTraceAsString()); } - Check Logs: After logging, check the
var/log/system.logor your custom log file in thevar/logdirectory for the logged messages and debug traces. - By following these steps, you can print debug traces and log error details in Magento 2 to help you troubleshoot issues effectively.
$traces = debug_backtrace();
foreach($traces as $trace){
var_dump($trace['class'] . '::' . $trace['function'] . '('.$trace['line'] .')');
}
die();You can print any object data by following code
echo "<pre>"; print_r(json_decode(json_encode($quote->getData()))); exit;
