FixEmptyLoggerPass.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bundle\MonologBundle\DependencyInjection\Compiler;
  11. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  12. use Symfony\Component\DependencyInjection\ContainerBuilder;
  13. use Symfony\Component\DependencyInjection\Reference;
  14. /**
  15. * Fixes loggers with no handlers (by registering a "null" one).
  16. *
  17. * Monolog 1.x adds a default handler logging on STDERR when a logger has
  18. * no registered handlers. This is NOT what what we want in Symfony, so in such
  19. * cases, we add a "null" handler to avoid the issue.
  20. *
  21. * Note that Monolog 2.x does not register a default handler anymore, so this pass can
  22. * be removed when MonologBundle minimum version of Monolog is bumped to 2.0.
  23. *
  24. * @author Fabien Potencier <fabien@symfony.com>
  25. *
  26. * @see https://github.com/Seldaek/monolog/commit/ad37b7b2d11f300cbace9f5e84f855d329519e28
  27. */
  28. class FixEmptyLoggerPass implements CompilerPassInterface
  29. {
  30. private $channelPass;
  31. public function __construct(LoggerChannelPass $channelPass)
  32. {
  33. $this->channelPass = $channelPass;
  34. }
  35. public function process(ContainerBuilder $container)
  36. {
  37. $container->register('monolog.handler.null_internal', 'Monolog\Handler\NullHandler');
  38. foreach ($this->channelPass->getChannels() as $channel) {
  39. $def = $container->getDefinition($channel === 'app' ? 'monolog.logger' : 'monolog.logger.'.$channel);
  40. foreach ($def->getMethodCalls() as $method) {
  41. if ('pushHandler' === $method[0]) {
  42. continue 2;
  43. }
  44. }
  45. $def->addMethodCall('pushHandler', [new Reference('monolog.handler.null_internal')]);
  46. }
  47. }
  48. }