Logs in Magento 2 consist the system information for the future analysis.
To enable the debug mode go to Stores -> Configuration -> Advanced -> Developer -> Debug -> Set ‘Yes’ to Log to file.
Also make sure Magento store is in developer mode. If Magento store is in Production Mode then need run the below command.
php bin/magento config:set dev/debug/debug_logging 1
Below are the Methods to print Log in Magento 2.
Method 1 : Using Helper Data
File : app/code/V4U/Helloworld/Helper/Data.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php namespace V4U\Helloworld\Helper; use \Magento\Framework\App\Helper\AbstractHelper; use Zend\Log\Writer\Stream; use Zend\Log\Logger; class Data extends AbstractHelper { public function printLog($log) { $writer = new Stream(BP . '/var/log/CustomLog.log'); $logger = new Logger(); $logger->addWriter($writer); $logger->info($log); } } |
Now you can call that Helper class where you want to print log.
File : app/code/[Vendor][Module][Path][fileName.php]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php namespace [Vendor]\[Module]\[Path]; use V4U\Helloworld\Helper\Data; class FileName { /** * The Helper Call From V4U Helloworld Module. * * @var Helper */ protected $helper; public function __construct(Data $helperName) { $this->helper = $helperName; } $this->helper->printLog('msg for print'); /*Use this in Function to print log*/ } |
You can review log on following path : var/log/CustomLog.log
Method 2 : Using Logger Interface (Factory Method)
You can add Logger Interface where you want to print log.
File : app/code/[Vendor][Module][Path][fileName.php]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php namespace [Vendor]\[Module]\[Path]; use Psr\Log\LoggerInterface; class FileName { /** * @var \Psr\Log\LoggerInterface */ private $logger; public function __construct(LoggerInterface $logger;) { $this->logger = $logger; } $this->logger->debug('msg to print'); // print var\log\debug.log /*Use this in Function to print log*/ $this->logger->info('msg to print'); // print var\log\system.log /*Use this in Function to print log*/ } |
Method 3 : Using ObjectManager
For var\log\system.log
1 |
\Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->info('Write Here To Print Log - System Log'); |
For var\log\debug.log
1 |
\Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->debug('Write Here To Print Log - Debug Log'); |
Method 4 : Temporary print log with new file
1 2 3 4 5 6 |
$myArrayVar = array("Vrajesh", "Patel"); $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/CustomLogFile.log'); $logger = new \Zend\Log\Logger(); $logger->addWriter($writer); $logger->info('Simple Text Log'); // To print Simple Text Log $logger->info('Array Log'.print_r($myArrayVar, true)); // To print Array Log |
You can implement any above method for debugging the code.
Happy Coding. Keep Liking & Sharing