How to create a log in Magento 2

Integrate Magepack with Magento/Adobe commerce

Add a log in Magento 2, We will learn to create a custom log file programmatically and log data into the custom log file.
If indeed your only concern is to log to a different file, there is a slightly easier way. Especially if you want to incorporate that to multiple modules or if you want different log files within your module. With this method, you don’t have to create custom handlers.
Magento 2 provides three types of default log files: debug.log, exception.log, and system.log. Even though we still can use these files to log data, sometimes we need to have our own custom log files. If you have ever wondered how to create a custom log file in Magento 2, then this is for you.

Write below code in PHTML file and PHP file

For example custom log file name integerbyte.log

Create log in Magento 2, directory is var/log/ from Magento root directory

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


$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/integerbyte.log');
$logger = new \Zend\Log\Logger();
$logger->info('Your text message');

Using Dependency Injection method

This is done by Dependency Injection. Below you will find a class that only writes a log entry

namespace YourNamespace\YourModule\Model;

class MyModel
     * Logging instance
     * @var \YourNamespace\YourModule\Logger\Logger
    protected $_logger;

     * Constructor
     * @param \YourNamespace\YourModule\Logger\Logger $logger
    public function __construct(
        \YourNamespace\YourModule\Logger\Logger $logger
    ) {
        $this->_logger = $logger;

    public function doSomething()
        $this->_logger->info('I did something');

Using objectmanger

$logger = \Magento\Framework\App\ObjectManager::getInstance()->get(\Psr\Log\LoggerInterface::class);

Write log in Magento 2, Include psr logger class in your file using use and then call addDebug() method. This will print log message in var/log/debug.log file

Hope this guide is useful for you to create a custom logger in Magento 2

Thank you for reading our blog and see you in the upcoming articles.

Related post Magento 2 speed optimization
Refer log file

Leave a Reply

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

Back To Top