0

I am trying to create a custom log and print the info message on button click in Magento 2, I have extended the monolog/loggger method but the custom log file is not created. Someone can you say what is wrong with my code. Adding code for your reference.

CreateSourceButton.php is my PHP where I included logger CreateSourceButton.php created inside the Block folder

di.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/config.xsd">
<type name="Magento\Search\Model\Adminhtml\System\Config\Source\Engine">
    <arguments>
         <argument name="engines" xsi:type="array">
             <item name="coveo" xsi:type="string">Coveo</item>
         </argument>
    </arguments>
</type>

<preference for="Dss\CoveoSearch\Api\Service\TrackingInterface"
                type="Dss\CoveoSearch\Model\Service\Tracking" />
                <preference for="Dss\CoveoSearch\Api\Service\ConfigInterface"
                type="Dss\CoveoSearch\Model\Service\Config" />
                
<!--Configuration code for logger in magento 2-->
<!--Handler class reference-->
<type name="Dss\CoveoSearch\Logger\Handler">
    <arguments>
        <argument name="filesystem" xsi:type="object">Magento\Framework\Filesystem\Driver\File</argument>
    </arguments>
</type>
<!--Logger class reference-->
<type name="Dss\CoveoSearch\Logger\Logger">
    <arguments>
        <argument name="name" xsi:type="string">Coveolog</argument>
    <argument name="handlers" xsi:type="array">
        <item name="system" xsi:type="object">Dss\CoveoSearch\Logger\Handler</item>
    </argument>
    </arguments>
</type>
</config>

Logger.php

<?php declare(strict_types=1);
namespace Dss\CoveoSearch\Logger;
class Logger extends \Monolog\Logger
{
}
?>

Handler.php

<?php declare(strict_types=1);
namespace Dss\CoveoSearch\Logger;
use Monolog\Logger;
class Handler extends \Magento\Framework\Logger\Handler\Base
{
    protected $loggerType = Logger::INFO;
    protected $fileName = '/var/log/coveo.log';
}
?>

CreateSourceButton.php

<?php
namespace Dss\CoveoSearch\Block\Adminhtml\Form\Field;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Data\Form\Element\AbstractElement;
class CreateSourceButton extends Field
{
    protected $_logger;
    protected $_template = 'Dss_CoveoSearch::system/button.phtml';
    public function __construct(\Dss\CoveoSearch\Logger\Logger $logger,
    Context $context, array $data = [])
    {
        $this->_logger = $logger;
        parent::__construct($context, $data);
    }
    public function doSomething()
    {
        $this->_logger->info('I did something');
    }
    public function getAjaxUrl()
    {
        return $this->getUrl('coveo/system/CreateSource');
    }
    
    public function render(AbstractElement $element)
    {
        $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
        return parent::render($element);
    }
    protected function _getElementHtml(AbstractElement $element)
    {
        return $this->_toHtml();
    }
    
    public function getCustomUrl()
    {
        return $this->getUrl('router/controller/action');
    }
    
    public function getButtonHtml()
    {
        $button = $this->getLayout()->createBlock(
            'Magento\Backend\Block\Widget\Button'
            )->setData(
                [
                    'id' => $this->getButtonId(),
                    'label' => __('Create'),
                    'on_click' => sprintf("location.href = '%s';", $this->doSomething()),
                ]
                );
            return $button->toHtml();
    }
    
    /**
     * @inheritdoc
     */
    public function getButtonId()
    {
        return 'create_source';
    }
    public function executeApi(){
        $jsonEncodedData = json_encode(array(
            'sourceType' => 'PUSH',
            'name' => 'DSS-Coveo_M2-Integration-B2C-product-en_US',
            'sourceVisibility' => 'SHARED',
            'pushEnabled' => true
        ));
        $bearer = ' xxd540c63c-c809-4093-8d04-6733869b1a92';
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://platform.cloud.coveo.com/rest/organizations/dsspartnersorggrc3y48w/sources",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $jsonEncodedData,
            CURLOPT_HTTPHEADER => array(
                'Content-type: application/json',
                'Accept: application/json',
                'Authorization: Bearer ' . $bearer
            )
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
}
7
  • Please check first you can create log file by using zend code, I don't think it will work on onClick you'r code is correct I think.
    – Ankit
    Commented Mar 29, 2021 at 5:12
  • I tried creating a log using the Zend and the log file is created on page load.
    – Ajmalriyaz
    Commented Mar 29, 2021 at 6:36
  • You have to give URL in it of Controller
    – Ankit
    Commented Mar 29, 2021 at 7:08
  • @Ankit can i get any example?
    – Ajmalriyaz
    Commented Mar 29, 2021 at 7:42
  • Please May I know after adding Logger what you want to do, I think you want to execute you'r executeApi() function right?
    – Ankit
    Commented Mar 29, 2021 at 7:47

1 Answer 1

0

please replace you'r code of onclick:

'onclick' => 'javascript:functionNameToBeCalled(); return false;',

Now write JS code in button.phtml and call ajax from it like:

require([
    'jquery',
    'prototype'
], function ($j) {

window.javascript:functionNameToBeCalled = function () { $j.ajax({}); };

In ajax call controller, have log in it and call Custom APIs.

NOTE Close the brackets carefully, do not copy paste code completely.

Please let me know if you required anything.

3
  • the API is called when I refresh the page, but I have written the function to be called on button click.
    – Ajmalriyaz
    Commented Mar 29, 2021 at 13:46
  • Yes for that you have to fire ajax request, please follow the steps you will get it and it will not run on page refresh.
    – Ankit
    Commented Mar 29, 2021 at 14:46
  • @Ajmalriyaz Please accept answer if you find solution satisfactory
    – Ankit
    Commented Mar 30, 2021 at 5:11

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.