Logs in Magento 2 consist of system information records for the analysis in the future. One of the most common examples of such events is the error log.
Developers know the pain of errors and the process to deliver a working solution. Debugging can be made easier for them by custom logs. It helps to spot an error and the reason for it, easily. Logs contribute to the visibility into Magento 2 system processes.
Now if you want to learn how to print log in Magento 2, you’re at the right place! I have come up with 3 different methods to print log in Magento 2.
- Using Helper Data
- Using Logger Interface
- Using Object Manager
Follow any of the below methods to create your own custom log files and get to solve the errors
Note:
- Make sure that the debug mode is enabled in the backend. Go to Stores -> Configuration -> Advanced -> Developer -> Debug and set “Yes” to Log to File.
- Make sure your Magento store is in developer mode.
- For production mode, you have to run the below command in shell:
bin/magento config:set dev/debug/debug_logging 1
Methods to Print Log in Magento 2
Method: 1 Using Helper Data
create file [Vendor][Module]HelperData.php
<?php namespace [Vendor]\[Module]\Helper; use Zend\Log\Writer\Stream; use Zend\Log\Logger; class Data extends AbstractHelper { public function printLog($log) { $writer = new Stream(BP . '/var/log/fileName.log'); $logger = new Logger(); $logger->addWriter($writer); $logger->info($log); } }
Simply call Helper class method where you want to print the log :
create file [Vendor]\[Module]\[Path]\[fileName.php]
<?php namespace [Vendor]\[Module]\[Path]; use [Vendor]\[Module]\Helper\Data; protected $helper; class FileName { public function __construct(Data $helperName) { $this->helper = $helperName; } $this->helper->printLog('msg for print');
Method 2: Using Logger Interface
To enable the log in custom extension, go to app\code\[Vendor]\[Module]\[Path]\[fileName.php] and add below code.
<?php namespace [Vendor]\[Module]\[Path]; use Psr\Log\LoggerInterface; class FileName { protected $logger; public function __construct(LoggerInterface $logger;) { $this->logger = $logger; } $this->logger->debug('msg to print'); // print var\log\debug.log $this->logger->info('msg to print'); // print var\log\system.log }
Method 3: Using Object Manager
To print the message in var\log\system.log:
\Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->info('msg to print');
Carry on your development process smoothly and if anytime you need to log variables or custom messages, you’ll be having the easy method!
Happy Debugging!