Skip to content

Instantly share code, notes, and snippets.

@BurningDog
Created September 10, 2020 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BurningDog/80904712a29ea849308a529be625fab1 to your computer and use it in GitHub Desktop.
Save BurningDog/80904712a29ea849308a529be625fab1 to your computer and use it in GitHub Desktop.
Symfony 4.4: using a Logger inside a Service
<?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);
}
}
@BurningDog
Copy link
Author

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 implement LoggerAwareInterface and somehow setLogger() magically gets called.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment