How to generate a custom log file in Magento 2

As we all know Magento is the most advanced featured eCommerce platform all around the world. Nowadays, most businesses are converting their online store to Magento. And that's too obvious because of its functionality and default features. Moreover, Magento 2 came up with more advanced functionalities compared to Magento 1. If we consider the log files then, It was easier to generate the log files in Magento 1. But, in Magento the method is different. So in our today's article, we will see how to generate a custom log file in  Magento 2.

Update your email service by switching to Sendinblue or GetResponse to get a better sales conversation.

How to generate a custom log file in Magento 2

In Magento 1, you can create a custom log file by using the Mage::log() method. Further, by changing the $file parameter of the log() method, you can easily save the logs into the custom file. However, Magento 2 is using Monolog(PHP logging solution). Additionally, Magento 2 has three kinds of default log files. The first one is debug.log, the second is exception.log, and lastly system.log. But still, sometimes we may have to create custom log files. So here is a step-by-step instruction for how to generate a custom log file in Magento 2. So let's get started.

1. Create a Module

Firstly, we have to create a basic module to determine the logs. To establish the new module with the Magento codebase, create a module.xml and registration.php file. However, you can also skip this step if you already have a module that you can use to create a custom logger.

We will use Milople as the namespace and Customlog as the module name.

registration.php - Milople/Customlog/registration.php.

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

module.xml - Milople/Customlog/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="Milople_Customlog">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>

Now, create a frontend router for testing purposes. Further, the module can also use a controller class to execute the custom logger.

routes.xml - Milople\Customlog\etc\frontend\routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="milople" frontName="customlog">
            <module name="Milople_Customlog"/>
        </route>
    </router>
</config>

2. Create a logger

After that, you need to create the logger and handler classes. Create a handler.php at Milople/Customlog/logger/. This handler class declares the custom log file. Additionally, it will also define its Magento root directory path.

<?php
namespace Milople\Customlog\Logger;

use Magento\Framework\Logger\Handler\Base as BaseHandler;
use Monolog\Logger;

class Handler extends BaseHandler
{
    /**
     * Logging level
     * @var int
     */
    protected $loggerType = Logger::WARNING;

    /**
     * File name
     * @var string
     */
    protected $fileName = '/var/log/mycustom.log';
}

The log file will be generated in {MagentoRoot}/var/log/mycustom.log.

3. Define the logger

Then, define the custom logger handle information in the di.xml file. The handler.php class will handle the logger class. Further, in this file, you are allowed to give a unique name to the handle.  Here, we have set "myCustomLogger".

di.xml - Milople\Customlog\etc\di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <type name="Milople\Customlog\Logger\Handler">
        <arguments>
            <argument name="filesystem" xsi:type="object">Magento\Framework\Filesystem\Driver\File</argument>
        </arguments>
    </type>
    <virtualType name="Milople\Customlog\Logger\Logger" type=”Monolog\Logger”>
        <arguments>
            <argument name="name" xsi:type="string">myCustomLogger</argument>
            <argument name="handlers" xsi:type="array">
                <item name="system" xsi:type="object">Milople\Customlog\Logger\Handler</item>
            </argument>
        </arguments>
    </virtualType>
    <type name=”Milople\Customlog\Controller\Index\Index”>
        <arguments>
            <argument name=”logger” xsi:type=”object”>Milople\Customlog\Logger\Logger </argument>
        </arguments>
    </type>
</config>

4. Test the logger

Lastly, when you complete creating the custom logger, now we have to test it. For that, create a basic controller class, that can be used for your custom logger to log data.

Index.php - Milople\Customlog\Controller\Index\Index.php

<?php
namespace Milople\Customlog\Controller\Index;

use \Psr\Log\LoggerInterface;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\View\Result\PageFactory;

class Index extends Action
{
    /**
     * @var PageFactory
     */
    protected $resultPageFactory;

    /**
     * @var JsonFactory
     */
    protected $resultJsonFactory;

    /**
     * @var LoggerInterface
     */
    protected $logger;

    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        JsonFactory $resultJsonFactory,
        LoggerInterface $logger
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->resultJsonFactory = $resultJsonFactory;
        $this->logger = $logger;
        parent::__construct($context);
    }

    public function execute()
    {
        // Our logger would not allow to use debug,info and notice log types
        $this->logger->debug('Log Debug');
        $this->logger->info('Log Info');
        $this->logger->notice('Log Notice');

        // We can use below log types via our custom log
        $this->logger->warning('Log Warning');
        $this->logger->error('Log Error');
        $this->logger->critical('Log Critical');
        $this->logger->alert('Log Alert');
        $this->logger->emergency('Log Emergency');

        $result = $this->resultJsonFactory->create();
        $data = ['message' => 'Hello world!'];

        return $result->setData($data);
    }
}

Run the below command after you finish.

bin/magento setup:upgrade
bin/magento cache:flush

Execute the created controller and see the data.

Wrapping Up

If you want to see your custom log file then, go to the {MagentoRoot}/var/log directory/. Here you will see the generated by mycustom.log. Moreover, follow all the above-listed steps to generate a custom log file in Magento 2. I wish this article will help you with how to generate a custom log file in Magento 2. Although, if you face any issues while generating the logs, feel free to contact us.