Magento 2 : How to add a logging function when debugging
When debugging, it might be necessary to add some logs.
Here is a simple way to add a logging function in your code.
Warning :
This is not supposed to stay in your code and is only for debugging purpose.
There are better and more integrated ways of doing it
<?php /** * @param $str */ private function log($str) { $str = 'CLASS : ' . str_pad(__CLASS__, 50, ' ') . ' - LINE : ' . str_pad(debug_backtrace()[0]['line'], 4, ' ') . ' - FUNCTION : ' . str_pad(debug_backtrace()[1]['function'] , 15, ' ') . ' - STR : ' . $str; $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); /** @var \Magento\Framework\Filesystem\DirectoryList $directory */ $directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList'); $rootPath = $directory->getPath(\Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR); $logger = new \Zend\Log\Logger(); $writer = new \Zend\Log\Writer\Stream($rootPath . '/log/zendlog.log'); $logger->addWriter($writer); $logger->debug($str); }