?> Magento 2 - Quick tip : how to log and debug easily - Addeos

Magento 2 – Quick tip : how to log and debug easily

Magento 2 – Quick tip : how to log and debug easily

Whatever the development you are doing, and whatever the environment and technology you are working on, you always need to debug your code.

Let's debug Magento 2 with logs.

This is how i have been processing for many times in a magento 2 environment and coding with PhpStorm IDE.

First, i have added 2 simple live templates inside my PhpStorm IDE.

The first one will allow me to temporarily and quickly add a logging function inside my code :

Here is the live template code if you need to copy paste it.

<?php
    private function log($str)
    {
        $str = 'CLASS : ' . str_pad(__CLASS__, 50, ' ')
            . ' - LINE : ' . debug_backtrace()[0]['line']
            . ' - 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::class);
        $rootPath = $directory->getPath(\Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR);
        $logger = new \Zend\Log\Logger();
        $writer = new \Zend\Log\Writer\Stream($rootPath . '/log/exception.log');
        $logger->addWriter($writer);
        $logger->debug($str);
    }

This logging function is not perfect but it allows you to log any info just like we could do with magento 1 and famous Mage::Log function. It also gives a little of contextual information, the PHP class, the PHP method and the line number where the log have been added.

Here is the second live template i have added :

It allows to quickly add a log in the code.

With these 2 live template i can easily and quickly temporarily add log in my code.

Here is how you add the logging function in your code :

And here is how you call it from anywhere in your code :

After that you will just need to open you command line and start a tail -f var/log/exception.log command and you will see the logs coming.

And that's all. Please remember that this is very temporary and must not live inside production code (directly using object manager is not a good practice) so don't forget to remove this function and calls before commiting you code.

berliozd