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!

Raphael at Digital Pianism
70.8k37 gold badges192 silver badges357 bronze badges
asked Sep 9, 2016 at 10:48
1

1 Answer 1

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.

answered Sep 9, 2016 at 11:00

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.