Sean Breeden

Full Stack PHP, Python, AI/ML Developer
"AI won’t replace you, but people who are using AI will replace you" --Anonymous

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();
$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.

Views: 2144
| Home | Announcements | Artificial Intelligence | Commodore 64 | CraftCMS | Crypto | Games | Geek | Machine Learning | Magento | Memes | Science News | Security | 7 Days to Die | Ubuntu |