Log file output anywhere in Magento 2 (updated)
Magento 2.4.2 or earlier:
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/my.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
Magento 2.4.2:
$writer = new \Laminas\Log\Writer\Stream(BP . '/var/log/my.log');
$logger = new \Laminas\Log\Logger();
$logger->addWriter($writer);
Magento 2.4.3+:
$writer = new \Zend_Log_Writer_Stream(BP . '/var/log/my.log');
$logger = new \Zend_Log();
$logger->addWriter($writer);
Output strings and arrays using the code above (all versions):
// Individual line or string output $logger->info('Single variable or line output: ' . $myString); // Dump an array $logger->info('Array: ' . print_r($myArray, true));
That's it. This will output to var/log/my.log. Keep in mind that print_r() will most likely run out of memory when outputting against an object in Magento 2. Try to use ->getData() when possible.