As the Magento core team continue to work Zend out of the application, we’re starting to see legacy libraries being fully dropped – including (annoyingly) the Zend logging class.

Before Magento 2.4.3, you used to be able to log anything in your code like this;


public function logThis($msg) {
		$date   = date("d-m-Y H:i:s");
		$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/pixie-log.log');
		$logger = new \Zend\Log\Logger();
		$logger->addWriter($writer);
		$logger->info($date.': '.$msg);
	}



Since Magento 2.4.3 you can’t use method of a Zend logger any more.


So how do we log to a custom log file now?

In your custom module, add the following to /etc/di.xml


<?xml version="1.0"?>
 <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="PixieMedia\Core\Logger\Handler">
        <arguments>
            <argument name="filesystem" xsi:type="object">Magento\Framework\Filesystem\Driver\File</argument>
        </arguments>
    </type>
    <type name="PixieMedia\Core\Logger\Logger">
        <arguments>
            <argument name="name" xsi:type="string">pixieLogger</argument>
            <argument name="handlers"  xsi:type="array">
                <item name="system" xsi:type="object">PixieMedia\Core\Logger\Handler</item>
            </argument>
        </arguments>
    </type>
</config>



Then in your module, create file /Logger/Handler.php


<?php

namespace PixieMedia\Core\Logger;
 
use Magento\Framework\Logger\Handler\Base;
use Monolog\Logger;
 
class Handler extends Base
{
    protected $loggerType = Logger::INFO;
 
    protected $fileName = '/var/log/pixiemedia_logger.log';
}



And finally, add /Logger/Logger.php


<?php

namespace PixieMedia\Core\Logger;
 
class Logger extends \Monolog\Logger
{
}



And now in any class you want to add logging, simply add this to your constructor;


public function __construct(
…
\PixieMedia\Core\Logger\Logger $pixieLogger
){
$this->_pixieLogger = $pixieLogger;
}



Then you can log like this;


$msg = 'Log this!';
$this->_pixieLogger->info($msg);



And then your log will appear in [mage root]/var/log/pixie_logger.log


[2021-09-01 12:54:27] pixieLogger.INFO: Log this!



While this does feel more restrictive - for example, not being able to declare the log filename on the fly, it does close a security risk and facilitate log cleaning on your declared log files.

Happy coding!