Magento & Magento 2 Logging Systems

Magento and Magento 2 logging systems

Logging system is one of the most useful tools in Magento. It really helps developers with the code debugging. By using the log files, they check how the web store works, see what problems are there, determine which of the functions work incorrectly. Today’s article describes the logging system in Magneto 2 and compares it with Magento 1.

Let’s start from the Mage::log() method in Magento 1!

public static function log($message, $level = null, $file = '', $forceLog = false);

It is well-known that using this function we are able to log any data that we need in Magento 1. It is simple enough.

However, the logging system in Magento 2 is different. It does not have the function sited above. It is replaced by Psr\Log\LoggerInterface that provides API for working with logging system. Below, there is the global preference for the interface used by Magento 2 by default:

<preference for="Psr\Log\LoggerInterface" type="Magento\Framework\Logger\Monolog" />

You use the Magento\Framework\Logger\Monolog class as an argument if you enter Psr\Log\LoggerInterface, for example:

<?php

namespace SomeNamespace;

use Psr\Log\LoggerInterface;

class MyClass

{

   /** @var  LoggerInterface */

   protected $logger;

   /**

    * @param LoggerInterface $logger

    * @param array $data

    */

   public function __construct(

       LoggerInterface $logger

   ) {

       $this->logger = $logger; // here will be object of Magento\Framework\Logger\Monolog class

                               // by default

   }

}

We offer you to look deeper in the source code of Psr\Log\LoggerInterface:

<?php

namespace Psr\Log;

interface LoggerInterface

{

   public function emergency($message, array $context = array());

   public function alert($message, array $context = array());

   public function critical($message, array $context = array());

   public function error($message, array $context = array());

   public function warning($message, array $context = array());

   public function notice($message, array $context = array());

   public function info($message, array $context = array());

   public function debug($message, array $context = array());

   public function log($level, $message, array $context = array());

}

Psr\Log\LoggerInterface is realized in accordance with RFC 5424. It includes the methods of information logging on all basic levels, which are provided by the RFC:

  • Emergency: system is unusable.
  • Alert: action must be taken immediately. 
  • Critical: critical conditions.
  • Error: error conditions.
  • Warning: warning conditions.
  • Notice: normal but significant condition.
  • Informational: informational messages.
  • Debug: debug-level messages.

And now, we need to check the Magento\Framework\Logger\Monolog class that implements Psr\Log\LoggerInterface:

<?php

namespace Magento\Framework\Logger;

use Monolog\Logger;

class Monolog extends Logger

{

   /**

    * Adds a log record.

    *

    * @param  integer $level   The logging level

    * @param  string  $message The log message

    * @param  array   $context The log context

    * @return Boolean Whether the record has been processed

    */

   public function addRecord($level, $message, array $context = [])

   {

       $context ['is_exception'] = $message instance of \Exception;

       return parent::addRecord($level, $message, $context);

   }

}

If have a closer look at that, the class simply extends Monolog APIs and performs it in the function of an intermediate layer.

Now, it is reasonable to look how to log some data to a file. To do it, you need to inject Psr\Log\LoggerInterface to the class that must use the logger and select the required logging level of the data. After that, you have to call the appropriate method of Psr\Log\LoggerInterface, for instance:

/** @var LoggerInterface $logger */

$logger->info('Important information', [

'context' => $context,

'something_else_should_be_logged' => $data,

])

By default, logged data locates in the next three files:

  • var/log/debug.log – all data saved by Psr\Log\LoggerInterface::debug() locates there.
  • var/log/exception.log – all exceptions data locates there.
  • var/log/system.log – data from the rest logging levels locates there.

There may be situations when you need to place the logs data to another file that differs from the default one. In such a case, you can set a new virtual type in order to extend the Magento\Framework\Logger\Monolog and rewrite the default “debug” handler by another one. The stages are sited below:

<virtualType name="Sam\CustomLogger\Logger\Custom" type="Magento\Framework\Logger\Monolog">

   <arguments>

       <argument name="handlers"  xsi:type="array">

           <item name="debug" xsi:type="object">Sam\CustomLogger\Logger\Handler\Custom</item>

       </argument>

   </arguments>

</virtualType>

Moreover, we just set that Magento must create the sample of the virtual type “Atwix\CustomLogger\Logger\Custom” in place of the default Magento\Framework\Logger\Monolog:

<type name="Sam\CustomLogger\Observer\Authenticated">

   <arguments>

       <argument name="logger" xsi:type="object">Sam\CustomLogger\Logger\Custom</argument>

   </arguments>

</type>

And after all, we get a class using the logger with custom handler:

<?php

namespace Sam\CustomLogger\Observer;

use Psr\Log\LoggerInterface;

use Magento\Framework\Event\ObserverInterface;

use \Magento\Framework\Event\Observer;

use Magento\Customer\Model\Customer;

class Authenticated implements ObserverInterface

{

   /** @var LoggerInterface  */

   protected $logger;

   public function __construct(

       LoggerInterface $logger

   )

   {

       $this->logger = $logger;

   }

   public function execute(Observer $observer)

   {

       /** @var Customer $customer */

       $customer = $observer->getModel();

       if ($customer->getId()) {

           $email = $customer->getEmail();

           $message = sprintf(' %s was logged in.', $customer->getName());

           $this->logger->debug($message, [

               'email' => $email,

           ]);

       }

       return $this;

   }

}

Now, a custom.log file locates in the var/log directory. It contains the next strings:

[2016-03-12 20:02:08] main.DEBUG: Lewis Carroll has been logged in. {"email":"lewi_car@example.com","is_exception":false} []

The full version of this instance is on GitHub.

Normally, the log files have more data about the website functioning. However, it consumes additional space on the hard disk. And due to the big size, it makes the logs reviewing process more difficult. But, you can fix it without any problems by cleaning the var/log directory. Let’s look below how to do it:

rm -rf var/log/*

So, to sum up we can say that Magento 2 still supports the logging system and it helps us to have a control over the website functioning. If you have some questions regarding this issue, we offer you to connect with our Magento development team and they will answer all of them! Also you can read the next article about Magento and Magento 2:

Comments (1):
Posted on Wednesday, September 14, 2016 by :
It's great to find soomene so on the ball
Leave a comment:
*Your comment will be published after approval by site administrator.