Magento 2 : Create custom logging

 

Magento 2 uses monolog library to log messages. You can check this library in following  path location in magento 2.

<magento_root_folder>/vendor/monolog/

Log file will be created inside var/log folder

If you want to use log in your custom module, you need to add instance of  monolog class in your custom file class. You need to pass the instance in the constructor of your custom class.

Go to app/code/yourCompany/yourModule/Block/custom.php

add following protected variable  in custom file class.

/**
* @var \Psr\Log\LoggerInterface
*/
protected $_logger;

add following parameter in your custom class  __construct()

\Psr\Log\LoggerInterface $logger

Now, we need to create an object

$this->_logger = $logger;
$this->_logger->addDebug('some text or variable');

Finally, constructor function looks like following

public function __construct(
        \Magento\Framework\View\Element\Context $context,
        \Magento\Cms\Model\Page $page,
        \Magento\Cms\Model\Template\FilterProvider $filterProvider,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Cms\Model\PageFactory $pageFactory,
        \Magento\Framework\View\Page\Config $pageConfig,
        \Psr\Log\LoggerInterface $logger,
        array $data = []
    ) {
        parent::__construct($context, $data);
        // used singleton (instead factory) because there exist dependencies on \Magento\Cms\Helper\Page
        $this->_page = $page;
        $this->_filterProvider = $filterProvider;
        $this->_storeManager = $storeManager;
        $this->_pageFactory = $pageFactory;
        $this->pageConfig = $pageConfig;
        $this->_logger = $logger;
        $this->_logger->addDebug('some text or variable');
    }

Here is the use of some predefined examples :

$this->_logger->addDebug($message); // log location: var/log/system.log
$this->_logger->addInfo($message); // log location: var/log/exception.log
$this->_logger->addNotice($message); // log location: var/log/exception.log
$this->_logger->addError($message); // log location: var/log/exception.log
$this->_logger->critical($e); // log location: var/log/exception.log
You can also write to the logs using the zend library
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/test.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('Your text message');