How to get events/observers in magento 2
-
13-12-2019 - |
Question
In Magento 1 I can get list of events/observers by debugging dispatchEvent()
method from Mage.php
like below.
/**
* Dispatch event
*
* Calls all observer callbacks registered for this event
* and multiple observers matching event name pattern
*
* @param string $name
* @param array $data
* @return Mage_Core_Model_App
*/
public static function dispatchEvent($name, array $data = array())
{
Mage::log($name,null,'Events');
Varien_Profiler::start('DISPATCH EVENT:'.$name);
$result = self::app()->dispatchEvent($name, $data);
Varien_Profiler::stop('DISPATCH EVENT:'.$name);
return $result;
}
In magento 2 where I can get list of events/observers?
Solution
You can do the same thing you did in Magento 1.x in the method \Magento\Framework\Event\Manager::dispatch()
.
but it's a difference. You don't have access to the logger.
You will have to inject an instance of the logger in the constructor.
protected $logger;
public function __construct(
InvokerInterface $invoker,
ConfigInterface $eventConfig,
\Psr\Log\LoggerInterface $logger
)
{
$this->_invoker = $invoker;
$this->_eventConfig = $eventConfig;
$this->logger = $logger;
}
Then you can call in the dispatch
method this:
$this->logger->info($message);
Instead of info
you can use all the methods from \Psr\Log\LoggerInterface
OTHER TIPS
Since this is for "quick debugging", you could avoid multiple edits by doing.
public function dispatch($eventName, array $data = [])
{
$logger = \Magento\Framework\App\ObjectManager::getInstance()->get(\Psr\Log\LoggerInterface::class);
$logger->info($eventName);
...
Location
/lib/internal/Magento/Framework/Event/Manager.php
@Marius answer is the correct solution.
In my case I can get list of all event by doing below changes which is very short cut like we do in mage.php file of magento1:
Note: I have only tested on magento2.1.1 version so I am not sure for any other version
\vendor\magento\framework\Event\Manager.php
public function dispatch
write below code to get all event in debug.log file after
$eventName = mb_strtolower($eventName);
near to line 56
\Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->debug($eventName);