cancel
Showing results for 
Search instead for 
Did you mean: 

magento 2 observer

magento 2 observer

In Magento 2 I'm trying to create an observer.

The objective is to call the method "eventLogging" when click "place order". To test the method, I send a basic message ("Hello") to a log file.

But nothing seems to happen when I "place order". What am I doing wrong?

/var/www/magento2/app/code/Myapp/Order/etc/frontend/events.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/Ev    ent/etc/events.xsd">
<event name="checkout_submit_before">
    <observer name="myapp_controller_success_action" instance="Myapp\Order\Observer\MyappObserver"   />
</event>

</config> 

/var/www/magento2/app/code/Myapp/Order/Observer

<?php 


namespace Myapp\Order\Observer;

use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;

class MyappObserver implements ObserverInterface {
public function __construct(

    \Psr\Log\LoggerInterface $logger
) {

    $this->logger = $logger;
}
public function eventLogging(\Magento\Framework\Object $observer) {

    $event = $observer->getEvent();
    $quote = $event->getQuote();

    $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/developer.log');
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($writer);
    $logger->info($quote->getData(),true); 
}
public function execute(Observer $observer) {

//  $event = $observer->getEvent();
 //   $quote = $event->getQuote();
        $myfile = fopen("var/log/debug.log", "a+") or die("Unable to open file!");
        fwrite($myfile, "hello");

fwrite($myfile, print_r($quote->getData(),true)); fclose($myfile); //$event = $observer->getEvent(); // $quote = $event->getQuote(); // Mage::log(print_r(Zend_Debug::dump($quote->getData()), true),NULL, 'developer.log'); exit; } /public function execute(\Magento\Framework\Event\Observer $observer) { rm_state()->controllerSet($observer['controller_action']); }/ }

1 REPLY 1

Re: magento 2 observer

Hello James

Place your event.xml in side the etc folder and outside the frontend.

i.e /var/www/magento2/app/code/Myapp/Order/etc/events.xml and event is "sales_order_place_after"

  

<config xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_order_place_after">
<observer name="coupan_applied" instance="Ipragmatech\Pricenegotiator\Observer\ApplycouponObserver"/>
</event>
</config>

 

  and inside your execute method use following code to just print log

 create "mylog.log" inside var/log/

  

        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/mylog.log');
	$logger = new \Zend\Log\Logger();
	$logger->addWriter($writer);
	$logger->info("Messsage"));