Magento logging: what is it and how to create it in Magento 2

Magento logging is a crucial part of every development process which provides insight into system processes of Magento 2. Also, it is a great tool for tracking errors, important events, exceptions and many more. When building a website or a module on Magento 2, it is important to create a log file to monitor/debug the errors.

What is Magento Logging?

Magento Logging is an essential part that provides insights for various system-related processes in Magento 2. Magento 2 comes with built-in logging solution based on Monolog Library which will be analyzed further in this post

The Main Magento log class is “Magento\Framework\Logger\Monolog” and is defined in “MAGENTO2_ROOT/app/etc/di.xml”

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

As mentioned before Monolog is a helpful logging tool that enables the Magento 2 user to utilize a wide range of handlers to their advantage which are logging to files and Syslog, sending alerts and e-mails, logging database activity, etc. Logger class comes with 8 levels of logs and methods for each of those levels, usage of these methods is based on the type of the message user is logging.

Magento Logging

Each of these way accepts 2 arguments, first one is the message itself ( string) and the second one is an optional array (for example instance of an Exception object)

$this->_logger-> emergency($message, array $context = array());  //saved in var/log/system.log 
$this->_logger-> alert($message, array $context = array())  //saved in var/log/system.log 
$this->_logger-> critical($message, array $context = array())  //saved in var/log/system.log 
$this->_logger-> error($message, array $context = array())  //saved in var/log/system.log 
$this->_logger-> warning($message, array $context = array())  //saved in  var/log/system.log 
$this->_logger-> notice($message, array $context = array())  //saved in var/log/system.log 
$this->_logger-> info($message, array $context = array())  //saved  in var/log/system.log
$this->_logger-> debug($message, array $context = array())  //saved in var/log/debug.log (does not work in production mode)

There is another way that can be used to log something with an arbitrary level passed as  first parameter

$this->_logger-> log($level, $message, array $context = array())

No matter what log level is used, are saved in var/log/exception.log

Create Magento logging in Magento 2

Default Magento 2 comes with built logging components based on the monolog library. But today, we are going to see how you can generate a custom log file using module programmatically in Magento 2. So, without further ado, let’s get started.

Firstly, you need to create a custom log file at the below path:

Step 1. Create file at given below path:

app\code\Vendor\Extension\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=”Vendor_Extension” setup_version=”1.0.0″ schema_version=”1.0.0″ />
</config>

Step 2. Create second file at given below path

app\code\Vendor\Extension\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=“Vendor\Extension\Logger\Handler”>

<arguments>

<argument name=“filesystem” xsi:type=“object”>Magento\Framework\Filesystem\Driver\File</argument>

</arguments>

</type>

<type name=“Vendor\Extension\Logger\Logger”>

<arguments>

 <argument name=“name” xsi:type=“string”>Extension</argument>

 <argument name=“handlers” xsi:type=“array”>

 <argument name=“handlers” xsi:type=“array”>

<item name=“system” xsi:type=“object”>Vendor\Extension\Logger\Handler</item>

</argument>

</arguments>

   </type>

</config>

Step 3. Create Third file at given below path:

app\code\Vendor\Extension\Logger\Handler.php

<?php

namespace Vendor\Extension\Logger;

use Monolog\Logger;

class Handler extends \Magento\Framework\Logger\Handler\Base

{

protected $loggerType = Logger::INFO;

protected $fileName = ‘/var/log/vendor_extension_log_file.log’;

}

Step 4. Create fourth file at given below path:

app\code\Vendor\Extension\Logger\Logger.php

<?php
namespace Vendor\Extension\Logger;
class Logger extends \Monolog\Logger
{
}

Step 5. Create fifth file at given below path:

app\code\Vendor\Extension\etc\crontab.xml

<?xml version=“1.0”?>

<config xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”xsi:noNamespaceSchemaLocation=“urn:magento:module:Magento_Cron:etc/crontab.xsd”>

<group id=“default”>

          <job name=“custom_cronjob”instance=“Vendor\Extension\Cron\Cronrun”method=“execute”>

        <schedule>0*/12***</schedule>

    </job>

</group>

</config>

Step 6. Create sixth file at given below path:

app\code\Vendor\Extension\Cron\Cronrun.php

<?php

namespaceVendor\Extension\Cron;

classCronrun

{

    protected$_logger;

    publicfunction__construct(

        \Vendor\Extension\Logger\Logger$logger

    ){

        $this->_logger=$logger;

    }

    publicfunctionexecute()

    {

        $this->_logger->info(“ Hello Thisisour Custom log file example”);

    }

}

After running this module, Your file will be created on below path -Magento2_root_directory\var\log\vendor_extension_log_file.log

Write the custom log in your module

In order to write the log in Magento 2, using the Monolog Library for the purpose of the logging is imperative. Monolog is a popular PHP logging solution. It has various handlers that generate sophisticated logging methods. Moreover, Its handlers include log to database, to files and syslog, email and alerts sending, etc. Each handler has the option of input message processing and propagation stopping or control passing to the next one in the chain.

We will point you to work with Monolog’s Logger class at MAGENTO_ROOT/vendor/monolog/monolog/src/Monolog/Logger.php.

Firstly, in your module, use one of the functions in app/code/Magesolution/HelloWorld/Block/Post.php. In this post, you will see some types of logs such as info, alert, notice, critical, error, and debug in the below code. However, keep in mind that all of them are gained in system.log file expecting from the debug log that is in debug.log file

<?php
namespace Magesolution\HelloWorld\Post;
class Post extends \Magento\Framework\View\Element\Template
{
protected $_logger;

public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Psr\Log\LoggerInterface $logger,
array $data = []
)
{
$this->_logger = $logger;
parent::__construct($context, $data);
}

public function testLogging()
{
// monolog’s Logger class
// MAGENTO_ROOT/vendor/monolog/monolog/src/Monolog/Logger.php

// saved in var/log/debug.log
$this->_logger->debug(‘debug1234’);
//Output: [2017-02-22 04:48:44] main.DEBUG: debug1234 {“is_exception”:false} []

$this->_logger->info(‘info1234’);
// Write to default log file: var/log/system.log
//Output: [2017-02-22 04:52:56] main.INFO: info1234 [] []

$this->_logger->alert(‘alert1234’);
// Write to default log file: var/log/system.log
//Output: [2017-02-22 04:52:56] main.ALERT: alert1234 [] []

$this->_logger->notice(‘notice1234’);
// Write to default log file: var/log/system.log
//Output: [2017-02-22 04:52:56] main.NOTICE: notice1234 [] []

// Write to default log file: var/log/system.log
$this->_logger->error(‘error1234’);
//Output: [2017-02-22 04:52:56] main.ERROR: error1234 [] []

// Write to default log file: var/log/system.log
$this->_logger->critical(‘critical1234’);
//Output: [2017-02-22 04:52:56] main.CRITICAL: critical1234 [] []

// Adds a log record at an arbitrary level
$level = ‘DEBUG’;
// saved in var/log/debug.log
$this->_logger->log($level,’debuglog1234′, array(‘msg’=>’123’, ‘new’ => ‘456’));
//Output: [2017-02-22 04:52:56] main.DEBUG: debuglog1234 {“msg”:”123″,”new”:”456″,”is_exception”:false} []

// Write to default log file: var/log/system.log
$level = ‘ERROR’;
$this->_logger->log($level,’errorlog1234′, array( array(‘test1’=>’123’, ‘test2’ => ‘456’), array(‘a’=>’b’) ));
//Output: [2017-02-22 04:52:56] main.ERROR: errorlog1234 [{“test1″:”123″,”test2″:”456”},{“a”:”b”}] []

}

}
?>

After that, you flush the Magento cache and check your result.

Conclusion

That’s all about Magento logging and methods to create it in Magento 2. If you still find it difficult to follow this guide or have any further questions regarding Magento 2, then you can get in touch with Magento experts for any free support. We are one of the leading Magento 2 extensions and theme providers. Also, we are one of the best Magento web development services providers in the world. With experienced Magento developers, we commit to providing high-quality products and services to help customers achieve their business success.