Logging Variables to Your Own File in Magento 2

Logging Variables to Your Own File in Magento 2

While building or fixing a module, it helps to dump values somewhere you can watch. These lines log to a file of your choosing in var/log.

The snippet

$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/logfilename.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info(__FILE__);

Use tail -f var/log/logfilename.log to watch output live. On Magento 2.4.4 and later, Zend classes are replaced by Laminas equivalents, so adjust the class names if needed.

Stuck on something similar? Our Magento development team is happy to take a look.

Keep reading

Related articles

All articles

Need a hand?

Stuck on something similar?
We can fix it with you.

Send us the problem. A senior developer reads every message and replies within one working day.