Magento 2 - How to add logs inside module
-
10-04-2021 - |
Вопрос
I have added like below way. But it doesn't work for that module
use Psr\Log\LoggerInterface;
/**
* @var LoggerInterface
*/
protected $logger;
protected $resultForwardFactory;
public function __construct(
Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\App\Response\Http\FileFactory $fileFactory,
\Magento\Framework\Translate\InlineInterface $translateInline,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Magento\Framework\View\Result\LayoutFactory $resultLayoutFactory,
\Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
\Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory,
LoggerInterface $logger
) {
$this->_coreRegistry = $coreRegistry;
$this->_fileFactory = $fileFactory;
$this->_translateInline = $translateInline;
$this->resultPageFactory = $resultPageFactory;
$this->resultJsonFactory = $resultJsonFactory;
$this->resultLayoutFactory = $resultLayoutFactory;
$this->resultRawFactory = $resultRawFactory;
$this->resultForwardFactory = $resultForwardFactory;
$this->logger = $logger;
parent::__construct($context);
}
/**
* @return void
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Exception
*/
public function run()
{
$this->resource->getConnection()->beginTransaction();
try {
$this->_prepare();
$this->_execute();
$this->resource->getConnection()->commit();
$this->logger->info('Test');
} catch (\Exception $e) {
$this->resource->getConnection()->rollBack();
$this->logger->info($e);
throw $e;
}
$this->getFlag()->save();
}
Решение
you can do this simple way ..
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/test.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('Your text message');
Другие советы
Your code seems correct to me.
if your run
function is executing, there should be log present in log file.
As per my observation you are looking in wrong log file.
if you added $this->logger->info('Test');
, Your log should be present in system.log
.
for more info please look at this
Не связан с magento.stackexchange