Magento 2

Logging approach

$this->_logger->addDebug($message);  // var/log/system.log
$this->_logger->addInfo($message); // var/log/system.log
$this->_logger->addNotice($message); // var/log/exception.log
$this->_logger->addError($message); // var/log/exception.log
$this->_logger->critical($e); // var/log/exception.log

Example of using logger

class Index
{
/**
* Logger instance
*
* @var \Psr\Log\LoggerInterface
*/
protected $_logger;
    /**
* @param \Psr\Log\LoggerInterface $logger
*/
public function __construct(
\Psr\Log\LoggerInterface $logger
) {
$this->_logger= $logger;
}
public function doSomething()
{
try {
//do something
} catch (\Exception $e) {
$this->getLogger()->critical($e);
}
}

/**
* Get logger instance
*
* @return \Psr\Log\LoggerInterface
*/
public function getLogger()
{
if (!$this->_logger instanceof \Psr\Log\LoggerInterface) {
$this->_logger = \Magento\Framework\App\ObjectManager::getInstance()->get(\Psr\Log\LoggerInterface::class);
}
return $this->_logger;
}
}
Like what you read? Give Trần Ngọc Đức a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.