Created
September 10, 2020 08:26
-
-
Save BurningDog/80904712a29ea849308a529be625fab1 to your computer and use it in GitHub Desktop.
Symfony 4.4: using a Logger inside a Service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Service; | |
use Psr\Log\LoggerAwareInterface; | |
use Psr\Log\LoggerInterface; | |
class MyLoggerService implements LoggerAwareInterface | |
{ | |
private LoggerInterface $logger; | |
/** | |
* Sets a logger instance on the object. | |
* | |
* @return void | |
*/ | |
public function setLogger(LoggerInterface $logger) | |
{ | |
$this->logger = $logger; | |
} | |
public function log(string $value) | |
{ | |
$this->logger->info($value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The official documentation is at https://symfony.com/doc/4.4/logging.html#using-a-logger-inside-a-service but doesn't include an example of what that service would look like. Here it is ^^
https://symfonycasts.com/screencast/symfony4-fundamentals/logger-trait is a helpful introduction, but their example didn't work for me. Turns out using
@required
is unnecessary - just implementLoggerAwareInterface
and somehowsetLogger()
magically gets called.