In today’s blog we will explain about Magento2 Custom Logs, but before that we will understand why we need logs and why we need custom logs.
What is Log?
Logs provides the visibiltiy that what is going in code process , It helps you to debug your code while running application. also you can store some helpful information like error if and when this error triggered.
Magento2 Provides 2 types of log, file based log and database log
Magento 2 Supports MonoLog which provides wide range of logging handlers
Magento has below inbuilt log functions
- alert()
- critical()
- debug()
- emergency()
- error()
- info()
- log()
- notice()
- warning()
Below is the example , how you can write a log for your module from magento’s default logging.
You need to inject \Psr\Log\LoggerInterface in your class
Below is example
<?php
namespace Mageacademy\LogExample\Plugin;
use Magento\Catalog\Api\ProductRepositoryInterface;
class ProductRepositoryPlugin
{
protected $logger;
public function __construct(
\Psr\Log\LoggerInterface $logger
) {
$this->logger = $logger;
}
public function aroundGet(ProductRepositoryInterface $subject,callable $proceed,$sku)
{
$this->logger->info(" Some Logging");
}
}
Write a Custom Log File
First of all you need to create a custom logger class file which will extend Magento\Framework\Logger\Handler\Base class
<?php
namespace Mageaccademy\LogExample\Logger;
use Magento\Framework\Logger\Handler\Base as BaseHandler;
use Monolog\Logger as MonologLogger;
class CustomLogger extends BaseHandler
{
/**
* Logging level
*
* @var int
*/
protected $loggerType = MonologLogger::ERROR;
/**
* File name
*
* @var string
*/
protected $fileName = '/var/log/mageacademy/customlogger.log';
}
Now Write a below code in di.xml file
<virtualType name="MyCustomLogger" type="Magento\Framework\Logger\Monolog">
<arguments>
<argument name="handlers" xsi:type="array">
<item name="error" xsi:type="object">Mageacademy\LogExample\Logger\CustomLogger</item>
</argument>
</arguments>
</virtualType>
<type name="Mageacademy\LogExample\Console\FirstCommand">
<arguments>
<argument name="logger" xsi:type="object">MyCustomLogger</argument>
</arguments>
</type>
Here you can see we have used virtual type and argument replacement feature, If you are not aware about it you can visit our Virtual Type in magento 2 and Argument Replacement in Magento2 Blog
Now you can below code to log your file
<?php
namespace Mageacademy\LogExample\Plugin;
use Magento\Catalog\Api\ProductRepositoryInterface;
class ProductRepositoryPlugin
{
protected $logger;
public function __construct(
\Psr\Log\LoggerInterface $logger
) {
$this->logger = $logger;
}
public function aroundGet(ProductRepositoryInterface $subject,callable $proceed,$sku)
{
$this->logger->info(" Some Logging");
}
}
Here you can use info , cirtical as per your requirement.
Hope you find my this blog , Please share with your friends and visit us again.