Table of Contents
In this article, I will teach you a very useful quick hack for Magento 2 developers. Here we will see how we can quickly log in a custom log file in Magento 2.
As you may know you can log using Psr\Log\LoggerInterface. But it will log in either system.log or debug.log file based on the log level.
You can also log to a custom file. So lets see the quickest way. The difference versions have different way for implementing this.
Log Data in Magento1:
Logging to a custom file was very easy in Magento 1 days. In Magento 1, you can log using just one line of code in a custom file as mentioned below.
Mage::log('text message', null, 'customfile.log');
Mage::log($myArray, null, 'customfile.log', true);
$myArray
is the array which we want to print in log file.
Log Data in Magento2.4.2 earlier versions:
So now let’s see, how we can achieve almost similar result in Magento 2.4.2 earlier versions.
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/customfile.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('text message');
$logger->info('Array Log'.print_r($myArray, true));
Log Data in Magento2.4.2 or after versions:
So now let’s see, how we can achieve almost similar result in Magento 2.4.2 or after this versions.
$writer = new \Laminas\Log\Writer\Stream(BP . '/var/log/customfile.log');
$logger = new \Laminas\Log\Logger();
$logger->addWriter($writer);
$logger->info('text message');
$logger->info('Array Log'.print_r($myArray, true));
Log Data in Magento2.4.3:
In Magento 2.4.3, we need to use below code scippet to the log in the custom file.
$writer = new \Zend_Log_Writer_Stream(BP . '/var/log/customfile.log');
$logger = new \Zend_Log();
$logger->addWriter($writer);
$logger->info('text message');
$logger->info('Array Log'.print_r($myArray, true));
This code is pretty self-explanatory. It will create a log file named customfile.log under var/log/ folder and log ‘I am logged
’ in it.
To print array use: $logger->info('Array Log'.print_r($myArray, true));
Conclusion:
In this article, we have seen the quickest way for logging the data in custom log file. The difference versions have different way for implementing this.
Thank you for reading the article. Please let us know your feedback on this article. We will love to hear back from you.