A QUICK WAY to print log or data in any PHP file in Magento 2

A QUICK WAY to print log or data in any PHP file in Magento 2

Hello Magento Folks, Welcome back to my learning blog. Today in this article I’m gonna show you a quick way to print log or print data in any PHP file in Magento 2.

Warning: Use this trick only for development local branches don’t use this to any production or live stores.

xdebug is the most powerful tool for PHPStrom to debug in Magento 2. But still sometime during development we need to print logs with proper output data so we use custom temporary logs to print data. So below I will give you a trick to print log with simple function which can access in any files in Magento 2.

You just need to create common functions in app/bootstrap.php which you can access to any PHP file of Magento 2.

So for example, Here I created functions to print logs in app/bootstrap.php

function printLog($myArray, $exit=0)
{
    $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/logfile.log');
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($writer);
    $logger->info('Array Log'.print_r($myArray, true)); // Array Log
    if ($exit) {
        exit;
    }
}

Here is the screenshot of common sample functions in my bootstrap.php

So I just need to call printLog($myData) function to print logs with custom file logfile.log

I use this method in Magento 2 projects which is setup in the localhost.

Hope this article will help you to quick write logs in Magento 2. If you have any questions feel free to comment below.

Thanks for reading. Keep sharing. Happy Coding 🙂