How to Create Custom Log File in Magento 2

While we develop Magento 2 website or module, it’s very important to create log file to debug/monitor the errors and system information. Magento 2 framework comes with built-in logger component which is based on Monolog library. You can find this Monolog library in the following location <Magento2_Root>/vendor/monolog.

The main Magento 2 log facility class is Magento\Framework\Logger\Monolog, and this is defined in the Magento2_Root/app/etc/di.xml file as follows:

<preference for="Psr\Log\LoggerInterface" type="Magento\Framework\Logger\Monolog" />
 
<type name="Magento\Framework\Logger\Monolog">
    <arguments>
        <argument name="name" xsi:type="string">main</argument>
        <argument name="handlers" xsi:type="array">
            <item name="system" xsi:type="object">Magento\Framework\Logger\Handler\System</item>
            <item name="debug" xsi:type="object">Magento\Framework\Logger\Handler\Debug</item>
        </argument>
    </arguments>
</type>

In the above code, the first line you can see a preference for LoggerInterface. Which means when the code requests a Psr\Log\LoggerInterface interface, an instance of Magento\Framework\Logger\Monolog will be supplied.

As you can also see that there is 2 parameters system and debug in handlers argument,

  • debug handler catches the messages with debug level and writes them into  Magento2_Root/var/log/debug.log file.
  • system handler catches the messages with other levels and writes them either to Magento2_Root/var/log/system.log file or to Magento2_Root/var/log/exception.log file in case of an exception.

Example to use the default logging file in Magento 2:

Here are some examples to use default logging functionality in Magento 2,

<?php
namespace YourNamespace\YourModule\Block;
class YourBlockFile extends \Magento\Framework\View\Element\Template
{
    protected $_logger;
 
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Psr\Log\LoggerInterface $logger,
        array $data = []
    ) {
        $this->_logger = $logger;
        parent::__construct($context, $data);
    }
 
    public function testLog() {
        $this->_logger->debug('debug message'); // This will be saved in Magento2_Root/var/log/debug.log
 
        $this->_logger->info('info message'); // This will be saved in Magento2_Root/var/log/system.log
 
        $this->_logger->alert('alert message'); // This will be saved in Magento2_Root/var/log/system.log
 
        $this->_logger->notice('notice'); // This will be saved in Magento2_Root/var/log/system.log
 
        $this->_logger->error('error message'); // This will be saved in Magento2_Root/var/log/system.log
 
        $this->_logger->critical('critical message'); // This will be saved in Magento2_Root/var/log/system.log
    }
}

Steps to create own custom log file in Magento 2:

You can also create your own log file in Magento 2 by follow the below steps,

Step 1: Define a new module,

Create a new XML file named module.xml in the below file path to define the new module,

File Path: app/code/MyModule/MyCustomLogger/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="MyModule_MyCustomLogger" setup_version="1.0.0">
    </module>
</config>

Next, create a file named registration.php in the below file path,

File Path: app/code/MyModule/MyCustomLogger/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'MyModule_MyCustomLogger',
    __DIR__
);

Step 2: Create a di.xml file in the below file path,

File Path: app/code/MyModule/MyCustomLogger/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="MyModule\MyCustomLogger\Logger\Handler">
        <arguments>
            <argument name="filesystem" xsi:type="object">Magento\Framework\Filesystem\Driver\File</argument>
        </arguments>
    </type>
    <type name="MyModule\MyCustomLogger\Logger\Logger">
        <arguments>
            <argument name="name" xsi:type="string">myCustomLogger</argument>
            <argument name="handlers" xsi:type="array">
                <item name="system" xsi:type="object">MyModule\MyCustomLogger\Logger\Handler</item>
            </argument>
        </arguments>
    </type>
</config>

Step 3: Create a PHP file named Handler.php in the below file path,

File Path: app/code/MyModule/MyCustomLogger/Logger/Handler.php

<?php
namespace MyModule\MyCustomLogger\Logger;
use Monolog\Logger;
class Handler extends \Magento\Framework\Logger\Handler\Base
{
    /**
     * Logging level
     * @var int
     */
    protected $loggerType = Logger::INFO;
 
    /**
     * File name
     * @var string
     */
    protected $fileName = '/var/log/my_custom_log.log';
}

Step 4: Create Logger.php file in the below file path,

File Path: app/code/MyModule/MyCustomLogger/Logger/Logger.php

<?php
namespace MyModule\MyCustomLogger\Logger;
class Logger extends \Monolog\Logger
{
}

Step 5: Finally, use the logger in your custom class file as follows,

<?php
namespace YourNamespace\YourModule\Block;
class YourBlockFile extends \Magento\Framework\View\Element\Template
{
    protected $_logger;
    
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \MyModule\MyCustomLogger\Logger\Logger $logger,
        array $data = []
    ) {
        $this->_logger = $logger;
        parent::__construct($context, $data);
    }
 
    public function testLog()
    {
        $this->_logger->info('info message'); // This will be saved in Magento2_Root/var/log/my_custom_log.log
    }
}

Hope this helps you.

Leave a Reply

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