Reading list Switch to dark mode

    Quickly Log in Custom File in Magento 2

    Updated 5 March 2024

    Hello, readers! 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 in using Psr\Log\LoggerInterface. But it will log in either the system.log or debug.log file based on the log level. You can also log to a custom file as mentioned in Magento2 Custom Log File Using Monolog blog. But it’s too much of work if you just want to log for debugging purposes.

    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('hello log', null, 'customfile.log');

    So now let’s see, how we can achieve an almost similar result in Magento 2.

    $writer = new \Zend_Log_Writer_Stream(BP .'/var/log/customfile.log');
    $logger = new \Zend_Log();
    $logger->addWriter($writer);
    $logger->info('hello log');

    This code is pretty self-explanatory. It will create a log file named customfile.log under var/log/ folder and log ‘hello log’ in it.

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    Thanks for reading the blog. Please share with fellow developers.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home