Back to Top

Create a custom log file in Magento 2 using Monolog and logging data into it.

Updated 28 June 2019

Hello everyone, Today we will learn to create a custom log file programmatically and log data into the custom log file.

First of all we need to create handlers and loggers for custom log file. For that, create a Logger.php class in Logger folder in your custom Module as shown below-

<?php
namespace YourNamespace\YourModule\Logger;

class Logger extends \Monolog\Logger
{
}
?>

After this, Create Handler class, in which we will define the custom Log file name as shown below-

<?php
namespace YourNamespace\YourModule\Logger;

use Monolog\Logger;

class Handler extends \Magento\Framework\Logger\Handler\Base
{
    protected $loggerType = Logger::INFO;

    protected $fileName = '/var/log/customLog.log';
}

Last step is to define the monolog in di.xml in etc folder of your custom Module –

<?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="YourNamespace\YourModule\Logger\Handler">
        <arguments>
            <argument name="filesystem" xsi:type="object">Magento\Framework\Filesystem\Driver\File</argument>
        </arguments>
    </type>
    <type name="YourNamespace\YourModule\Logger\Logger">
        <arguments>
            <argument name="name" xsi:type="string">myLoggerName</argument>
            <argument name="handlers"  xsi:type="array">
                <item name="system" xsi:type="object">YourNamespace\YourModule\Logger\Handler</item>
            </argument>
        </arguments>
    </type>
</config>

This is it, now just use the logger in your Magento 2 file, to print the logs in the custom created log file with the following code-

Start your headless eCommerce
now.
Find out More
<?php
namespace YourNamespace\YourModule\Model;

class TestModel
{
    protected $_logger;

    public function __construct(
        \YourNamespace\YourModule\Logger\Logger $logger
    ) {
        $this->_logger = $logger;
    }

    public function testFunction()
    {
        $this->_logger->info('This is test Data to be print in customLog.log file');
    }
}

Now you can find the above printed data in var/log/customLog.log file.

You can use this for logging any required data in your custom Module.

This is all for now, I ll be back soon.

. . .

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