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!
- 
 1follow this link magento.stackexchange.com/questions/75935/… I hope this is usefull for you...Rajkumar Elumalai– Rajkumar Elumalai2016年09月09日 10:58:25 +00:00Commented Sep 9, 2016 at 10:58
 
1 Answer 1
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:
- use 
\Psr\Log\LoggerInterfacebut you won't be able to write to a custom class - create your own log class based on 
Monolog\Logger: Logging to a custom file in Magento 2 
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.