Etienne
Etienne

Reputation: 420

Symfony3 logger as a service

I have custom class in my symfony application and I am trying to implement the logger in it, but without success. I have tryed to made a service like this :

#in app/config/services.yml
services:
    ControlLib.logger.monolog:
        class: My\TestBundle\Lib\ControlsLib
        arguments: ["@logger"] 
        tags:
            - { name: monolog.logger}

#in My/TestBundle/Lib/ControlsLib
class ControlsLib { 
 private $logger;

 public function __construct(LoggerInterface $logger    ) {
    $this->logger = $logger;
 }

 public function mainControl() {
     $this->logger->info(var_export('In my lib',true));
 }
}

I have this message when I call my function

Catchable Fatal Error: Argument 1 passed to 
My\TestBundle\Lib\ControlsLib::__construct() must be an instance of 
Symfony\Component\HttpKernel\Log\LoggerInterface, none given

Upvotes: 0

Views: 1836

Answers (1)

COil
COil

Reputation: 7586

Tested your code and it works as expected:

AppBundle/Lib/ControlsLib.php:

namespace AppBundle\Lib;

use Psr\Log\LoggerInterface;

class ControlsLib
{
    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function mainControl()
    {
        $this->logger->info(var_export('In my lib',true));
    }
}

app/config/services.yml:

services:
    controllib.logger.monolog:
        class: AppBundle\Lib\ControlsLib
        arguments: ["@logger"]
        tags:
            - { name: monolog.logger}

AppBundle/Controller/AppController.php:

$this->get('controllib.logger.monolog')->mainControl();
dump($this->get('controllib.logger.monolog')); die();
AppController.php on line 32:
ControlsLib {#108 ▼
  -logger: Logger {#107 ▼
    #name: "app"
    #handlers: array:2 [▶]
    #processors: array:2 [▶]
    #microsecondTimestamps: true
  }
}

Note that you service name should be lower-case as symfony will lower-case it automatically.

Upvotes: 2

Related Questions