"The secret of getting ahead is getting started." --Mark Twain

Log file output anywhere in Magento 2 (updated)

Monday, February 7th, 2022

Magento 2.4.2 or earlier:

$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/my.log');
$logger = new \Zend\Log\Logger();

Magento 2.4.2:

$writer = new \Laminas\Log\Writer\Stream(BP . '/var/log/my.log');
$logger = new \Laminas\Log\Logger();

Magento 2.4.3+:

$writer = new \Zend_Log_Writer_Stream(BP . '/var/log/my.log');
$logger = new \Zend_Log();

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.

Views: 1707