2

I want to log info to a specific file in magento2.

This does the job:

$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/test.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('Your text message');

but I want to use it with DI.

I am getting this error:

Missing required argument $streamOrUrl of Zend\Log\Writer\Stream.  

I am not sure about the syntax of DI when there are required parameters. Tried a few ways but it doesn't work:

use Zend\Log\Writer\Stream;
use Zend\Log\Logger;

    public $logger;

    public $writer;

    public function __construct(
        Logger $logger,
        Stream $writer
    ) {
        $this->logger = $logger;
        $this->writer = $writer;
        $this->logger->addWriter($this->writer(BP . '/var/log/test.log'));
        $this->logger->info('Start');
    }

If someone can show me how to use \Psr\Log\LoggerInterface to write to a custom log file it will be even better.

Thanks!

2

Unfortunately I don't think you can do that via DI.

The problem, as the error mentions, is that the first argument of Zend\Log\Writer\Stream is required and AFAIK, DI does not let you specify an argument when injecting classes.

Two possible solutions here:

Possible alternative

This needs to be tested but I think you can create your own class extending Zend\Log\Writer\Stream

Then in your di.xml you can specify the argument:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Vendor\Module\Model\My\Log\Class">
        <arguments>
            <argument name="streamOrUrl" xsi:type="string">/var/log/test.log</argument>
        </arguments>
    </type>
</config>

Then you can inject that class in your constructor.

Theorically I think that could work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.