0

I created a custom log for my module like this

app/etc/di.xml

<?xml version="1.0"?>
 <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Vendor\Module\Logger\Handler">
        <arguments>
            <argument name="filesystem" xsi:type="object">Magento\Framework\Filesystem\Driver\File</argument>
        </arguments>
    </type>
    <type name="Vendor\Module\Logger\Logger">
        <arguments>
            <argument name="name" xsi:type="string">TestLogger</argument>
            <argument name="handlers"  xsi:type="array">
                <item name="system" xsi:type="object"> Vendor\Module\Logger\Handler</item>
            </argument>
        </arguments>
    </type>
</config>

app/code/Vendor/Module/Logger/Handler.php

namespace Vendor\Module\Logger;
 
use Magento\Framework\Logger\Handler\Base;
use Monolog\Logger;
 
class Handler extends Base
{
    protected $loggerType = Logger::INFO;
 
    protected $fileName = '/var/log/testing.log';

}

app/code/Vendor/Module/Logger/Logger.php

namespace Vendor\Module\Logger;
 
class Logger extends \Monolog\Logger
{
    
}

This is how i making use of the log:

public function __construct(
…
\Vendor\Module\Logger\Logger $logger
){
$this->_logger = $logger;
}

$this->_logger('in');

the problem is it always log the text in new line, i need to the log file is set to empty first then the log message can be written, how can i achieve this ?

1
  • Please check the first answer below Commented Mar 23, 2022 at 9:53

1 Answer 1

0

You can do that whenever you log anything first delete that file and then run the logger code.

Add the the Below Function in the helper file and you can call it from anywhere.

public function clearLogs()
{
    $_file = $this->_objectManager->get('\Magento\Framework\Filesystem\Driver\File');
    $logDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')
        ->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::LOG)->getAbsolutePath();
    $fileName = 'testing.log'; // your Log File Name
    $fullPath = $logDirectory . $fileName;
    if ($_file->isExists($fullPath))  {
        $_file->deleteFile($fullPath);
    }
}

After that Use like this way.

$this->clearLogs();
$this->_logger('in');

Note : Ignore the Use of ObjectManager, add the dependencies in the constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.