0

How to create an custom event and observer for that event at backend in Magento2. For example I want to create an event that whenever an admin deletes a customer profile a separate log file is generated. Please help me with the detailed solution and the directory structure.

Savan Patel
  • 2,348
  • 1
  • 16
  • 39
Naiwrita09
  • 73
  • 1
  • 10

1 Answers1

0

You can achieve this using plugin instead of events

Create di.xml in app/code/Vendor/Module/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="Magento\Customer\Model\ResourceModel\CustomerRepository">
        <plugin name="customer_delete_around" type="Vendor\Module\Plugin\aroundCustomerDelete" />
    </type>
</config>

And create a plugin with below code in Vendor\Module\Plugin\aroundCustomerDelete.php

<?php

namespace Vendor\Module\Plugin;

class aroundCustomerDelete
{
    public function aroundDeleteById(
        \Magento\Customer\Model\ResourceModel\CustomerRepository $subject,
        \Closure $proceed,
        $customerId
    ) {
        // This will proceed delete action
        $result = $proceed($customerId);

        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/test.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        $logger->info('Your text message');

        return $result;
    }
}

Or you can create a custom log file using This link

Or use customer_delete_before this event to run your script in observer

Ranganathan
  • 3,220
  • 2
  • 18
  • 37