Logging is an important part of any development process. Logs assist you to spot an error and the reason for it. Magento 2 contains built-in logging solution based on Monolog Library.
To start working with a logger, you must create an instance of \Psr\Log\LoggerInterface. With this interface, you can call the following functions to write data to log files:
alert()
critical()
debug()
emergency()
error()
info()
log()
notice()
warning()
All log methods contains 2 arguments, first one is the message text and the second one is an optional array.
$this->_logger-> emergency($message); //saved in var/log/system.log $this->_logger-> alert($message); //saved in var/log/system.log $this->_logger-> critical($message); //saved in var/log/system.log $this->_logger-> error($message); //saved in var/log/system.log $this->_logger-> warning($message); //saved in var/log/system.log $this->_logger-> notice($message); //saved in var/log/system.log $this->_logger-> info($message); //saved in var/log/system.log $this->_logger-> debug($message); //saved in var/log/debug.log
Note: The degug log is not generate when your Magento 2 website is in production mode.
Below is an example of how to use logger in a custom method and how to log an exception.
protected $_logger;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Psr\Log\LoggerInterface $logger,
array $data = []
)
{
$this->_logger = $logger;
parent::__construct($context, $data);
}
public function customMethod()
{
$this->_logger->info('Info Message');
// Log as an Exception
try {
//do something
} catch (\Exception $e) {
$this->_logger->critical('Something went wrong', ['exception' => $e]);
}
}Thats it. Enjoy Magento 2!!


May 6, 2020 at 1:57 pm
Interesting information I got from here… Thanks, team!