Define a service with lazy loading logger in symfony

How to inject in a Symfony service the Logger component in lazy mode using DI. My intention is to log information in some methods. The logger instance must be created at the first time is used.

Something like this:

namespace AppServices;

use PsrLogLoggerInterface;

class XxxService{
    private $logger;

    public function some_method(){
      echo "method without logging"
      return $this;
    }

    private function _log($text){
        if(!$this->logger) $this->logger = new LoggerInterface(); //wrong approach creating object from Interface
        $this->logger->info($text)
    }

    public funtion method_withlog(){
        $this->_log("text logged")
        return $this;
    }
}

(new XxxService()))
    ->some_method()
    ->method_withlog() //here is created
    ->some_method()->method_withlog();

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *