Magento 2 logging

Today we are going to talk about Magento 2 logging. Logging is the most effective and important way for developers to find out where things are going wrong in their code. Magento 2 comes with built-in logging feature which is based on Monolog library. You can find this library under “/vendor/monolog” of your Magento 2 installation. Magento 2 logging can also be achieved by using Zend logger library, we are going to cover several approaches below

There are several ways you can achieve creating Magento 2 logging either in system.log or exception.log under /var/ of your Magento 2 installation. But today we are going to cover two simple way of doing it, one is with dependency injection and one is without dependency injection.

Let’s start with simple one first using Zend logger library

$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/custom.log');
 
$logger = new \Zend\Log\Logger();
 
$logger->addWriter($writer);
 
$logger->info("My first log is created under /var/log/custom.log");

The above will allow you to add your custom log file in var/log. It comes with the following severity options :-

$logger->info("My first info log is created under /var/log/custom.log");
 
$logger->debug("My first debug log is created under /var/log/custom.log");
 
$logger->emerg("My first emerg log is created under /var/log/custom.log");
 
$logger->alert("My first alert log is created under /var/log/custom.log");
 
$logger->crit("My first crit log is created under /var/log/custom.log");
 
$logger->err("My first err log is created under /var/log/custom.log");
 
$logger->warn("My first warn log is created under /var/log/custom.log");
 
$logger->notice("My first notice log is created under /var/log/custom.log");

Second option is to use Monolog library

<?php
namespace Scommerce\Custom\Model;
  
class Custom{
    protected $_logger;
 
    public function __construct(
        \Psr\Log\LoggerInterface $logger,
        array $data = []
    ) {
        $this->_logger = $logger;
        parent::__construct($data);
    }
    public function customMethod() {
        /*
        your custom method code
        */
 
        $this->_logger->addDebug('My first debug log is created under /var/log/system.log');
    }
}

It also comes with the following severity options which you will be able to call using the following code :-

$this->_logger->addInfo("My first info log is created under /var/log/system.log");
 
$this->_logger->addDebug("My first debug log is created under /var/log/system.log");
 
$this->_logger->addNotice("My first notice log is created under /var/log/system.log");
 
$this->_logger->addWarning("My first warning log is created under /var/log/system.log");
 
$this->_logger->addAlert("My first alert log is created under /var/log/system.log");
 
$this->_logger->addError("My first error log is created under /var/log/exception.log");
 
$this->_logger->addCritical("My first critical log is created under /var/log/exception.log");
 
$this->_logger->addEmergency("My first emergency log is created under /var/log/exception.log");

The above will allow you to add the logging in any of your custom module using dependency injection and if you are using some of the Magento classes like \Magento\Framework\View\Element\Template then you don’t need to add dependency in your constructor as it is already part of the template class.

Third option is to create your own handler

Step 1 – Create di.xml file in your custom module under \Scommerce\Custom\etc

<type name="Scommerce\Custom\Logger\Handler">
    <arguments>
        <argument name="filesystem" xsi:type="object">Magento\Framework\Filesystem\Driver\File</argument>
    </arguments>
</type>
<type name="Scommerce\Custom\Logger\Logger">
    <arguments>
        <argument name="name"      xsi:type="string">Scommerce/Custom</argument>
        <argument name="handlers"  xsi:type="array">
            <item name="debug"     xsi:type="object">Scommerce\Custom\Logger\Handler</item>
        </argument>
    </arguments>
</type>

Step 2 – Create Handler.php file in your custom module under \Scommerce\Custom\Logger\

namespace Scommerce\Custom\Logger;
 
/**
 * Class Handler
 * @package Scommerce\Custom\Logger
 */
class Handler extends \Magento\Framework\Logger\Handler\Base
{
    /**
     * @var string
     */
    protected $fileName = '/var/log/custom.log';
}

Step 3 – Create Logger.php file in your custom module under \Scommerce\Custom\Logger\

namespace Scommerce\Custom\Logger;
 
/**
 * Class Logger
 * @package Scommerce\Custom\Logger
 */
class Logger extends \Magento\Framework\Logger\Monolog
{
 
}

Step 4 – Use the logger in your custom class

namespace Scommerce\Custom\Model;
 
/**
 * Class Handler
 * @package Scommerce\Custom\Logger
 */
class CustomClass
{
 
/**
* @var \Scommerce\Custom\Logger\Logger
*/
protected $_logger;
 
 
/**
* @param \Scommmerce\Custom\Logger\Logger $logger
*/
public function __construct(
    \Scommmerce\Custom\Logger\Logger $logger
{
    $this->_logger = $logger;
}
 
}

It also comes with the following severity options which you will be able to call using the following code :-

$this->_logger->addInfo("My first info log is created under /var/log/custom.log");
 
$this->_logger->addDebug("My first debug log is created under /var/log/custom.log");
 
$this->_logger->addNotice("My first notice log is created under /var/log/custom.log");
 
$this->_logger->addWarning("My first warning log is created under /var/log/custom.log");
 
$this->_logger->addAlert("My first alert log is created under /var/log/custom.log");
 
$this->_logger->addError("My first error log is created under /var/log/custom.log");
 
$this->_logger->addCritical("My first critical log is created under /var/log/custom.log");
 
$this->_logger->addEmergency("My first emergency log is created under /var/log/custom.log");

Fourth option is to use the Laminas\Log\Logger class

One possible way to add logging using direct classes in Magento 2 is to use the Laminas\Log\Logger class, which is a third-party library that Magento 2 uses for logging. You can use this class to write log messages to any file of your choice, without involving the constructor dependency injection and running setup:di:compile every time. However, this method is not recommended, as it bypasses the Magento 2 best practices and standards for logging.

  • Install the Laminas\Log module using composer, as Magento 2.4.3 and later versions have removed this module. You can run the command composer require laminas/laminas-log to install it.
  • Create a writer object using the Laminas\Log\Writer\Stream class, and pass the file path of your custom log file as a parameter. For example, $writer = new \\Laminas\\Log\\Writer\\Stream(BP . ‘/var/log/custom.log’);
  • Create a logger object using the Laminas\Log\Logger class, and add the writer object to it using the addWriter method. For example, $logger = new \\Laminas\\Log\\Logger(); $logger->addWriter($writer);
  • Use the logger object to write log messages to your custom log file, using the methods for different log levels, such as info, notice, warn, error, etc. For example, $logger->info(‘Hello World!’);

Fifth Option:- Print Messages to the System and Debug Logs

To print string Output in system.log.

The code snippet below allows you to print a string output in the system.log file. To use it, simply replace 'Your Message' it with the actual message you want to log. This method is particularly useful for logging informational messages during Magento 2 development or troubleshooting processes.

\Magento\Framework\App\ObjectManager::getInstance()
    ->get('Psr\Log\LoggerInterface')->log('info','Your Message');

To print string Output in debug.log

The code snippet below allows you to print a string output in the debug.log file. To use it, replace 'Your Message' it with the desired message for debugging. Debug logging is valuable for capturing detailed information, such as variable values, function outputs, or code execution paths, aiding in the identification and resolution of issues within your Magento 2 environment.

\Magento\Framework\App\ObjectManager::getInstance()
   ->get('Psr\Log\LoggerInterface')->debug('Your Message');

Some of the above methods don’t work on Magento 2.4.3+

Some of the methods here don’t work on the newer versions of Magento as some of the modules have been removed from the newer versions. If you still wish to use these methods you need to follow the instructions below:-

  • Zend Logger Library:- In order to use this method in the newer versions of Magento you will have to install the Zend library additionally on your store. To do this run the following command:-
composer require magento/zendframework1
  • Monolog Logger Library:- In order to use this method in the newer versions of Magento you will have to install the Monolog library additionally on your store. To do this run the following command:-
composer require monolog/monolog
  • Laminas Logger Class:- In order to use the Laminas Logger class in the newer versions of Magento you will have to explicitly install this class using the command below:-
composer require laminas/laminas-log

Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.

Leave a Reply

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