"4, 8, 15, 16, 23 and 42" --LOST

Log file output anywhere in Magento 2

Saturday, May 1st, 2021

The correct and Magento-proper way to add a log file is to inject the \Psr\Log\LoggerInterface class into the constructor to call the logger object. However, this is not always practical, especially when you need a quick output. Here's a simpler way to temporarily output to a text log file from anywhere in Magento 2.

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

// Individual line or string output
$logger->info('Single variable or line output: ' . $stringValue);

// Dump an array
$logger->info('Array: ' . print_r($arrayValue, 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: 80