In magento 2, custom log file is important to verify the log for specific critical function implementation and debug the issues in the server level
Custom log file can be created by simply creating two virtual classes.
Virtual class definition in di.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
* di
*
* @copyright Copyright © 2021 Vasan. All rights reserved.
* @author survasp@gmail.com
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<virtualType name="Vasan\CustomLog\Model\Service\LogHandler" type="Magento\Framework\Logger\Handler\Base">
<arguments>
<argument name="fileName" xsi:type="string">/var/log/cust.log</argument>
</arguments>
</virtualType>
<virtualType name="Vasan\CustomLog\Model\Service\Logger" type="Magento\Framework\Logger\Monolog">
<arguments>
<argument name="handlers" xsi:type="array">
<item name="debug" xsi:type="object">Vasan\CustomLog\Model\Service\LogHandler</item>
</argument>
</arguments>
</virtualType>
<type name="Vasan\CustomLog\Model\Service">
<arguments>
<argument name="logger" xsi:type="object">Vasan\CustomLog\Model\Service\Logger</argument>
</arguments>
</type>
</config>
Service class to give the debug message
<?php
/**
* Service
*
* @copyright Copyright © 2021 Vasan. All rights reserved.
* @author survasp@gmail.com
*/
namespace Vasan\CustomLog\Model;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Psr\Log\LoggerInterface;
class Service
{
const XML_PATH_DEBUG = 'customlog/service/debug_enabled';
/**
* @var LoggerInterface
*/
protected $logger;
/**
* @var ScopeConfigInterface
*/
protected $scopeConfig;
/**
* @param LoggerInterface $logger
* @param ScopeConfigInterface $scopeConfig
*/
public function __construct(
LoggerInterface $logger,
ScopeConfigInterface $scopeConfig
) {
$this->logger = $logger;
$this->scopeConfig = $scopeConfig;
}
/**
* @param $message
*/
public function log($message)
{
$isDebugEnabled = $this->scopeConfig->getValue(static::XML_PATH_DEBUG);
if ($isDebugEnabled) {
$this->logger->debug($message);
}
}
}
Posted by vasan to vasan's deck (2021-09-24 07:20)