Symfony autowiring monolog渠道

问题描述 投票:8回答:6

在这个documentation之后,我可以创建许多渠道,用以下名称创建服务monolog.logger.<channel_name>

如何通过DI注入和自动装配将这些服务注入我的服务?

class FooService
{
    public function __construct(LoggerInterface $loggerInterface) {  }
}

YAML

#existing
foo_service:
    class: AppBundle\Services\FooService
    arguments: ["@monolog.logger.barchannel"]
# what I want to do
foo_service:
    autowire: true # how to inject @monolog.logger.barchannel ? 
symfony monolog symfony-3.2
6个回答
8
投票

我写了(也许更复杂)的方法。我不想标记我的自动服务,以告诉symfony使用哪个频道。使用symfony 4与php 7.1。

我使用monolog.channels中定义的所有其他通道构建了LoggerFactory。

我的工厂是捆绑的,所以在Bundle.php中添加

$container->addCompilerPass(
    new LoggerFactoryPass(), 
    PassConfig::TYPE_BEFORE_OPTIMIZATION, 
    1
); // -1 call before monolog

在monolog.bundle之前调用此编译器是很重要的,因为传递后的monolog会从容器中删除参数。

现在,LoggerFactoryPass

namespace Bundle\DependencyInjection\Compiler;


use Bundle\Service\LoggerFactory;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class LoggerFactoryPass implements CompilerPassInterface
{

    /**
     * You can modify the container here before it is dumped to PHP code.
     * @param ContainerBuilder $container
     * @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
     * @throws \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException
     */
    public function process(ContainerBuilder $container): void
    {
        if (!$container->has(LoggerFactory::class) || !$container->hasDefinition('monolog.logger')) {
            return;
        }

        $definition = $container->findDefinition(LoggerFactory::class);
        foreach ($container->getParameter('monolog.additional_channels') as $channel) {
            $loggerId = sprintf('monolog.logger.%s', $channel);
            $definition->addMethodCall('addChannel', [
                $channel,
                new Reference($loggerId)
            ]);
        }
    }
}

和LoggerFactory

namespace Bundle\Service;

use Psr\Log\LoggerInterface;

class LoggerFactory
{
    protected $channels = [];

    public function addChannel($name, $loggerObject): void
    {
        $this->channels[$name] = $loggerObject;
    }

    /**
     * @param string $channel
     * @return LoggerInterface
     * @throws \InvalidArgumentException
     */
    public function getLogger(string $channel): LoggerInterface
    {
        if (!array_key_exists($channel, $this->channels)) {
            throw new \InvalidArgumentException('You are trying to reach not defined logger channel');
        }

        return $this->channels[$channel];
    }
}

所以,现在你可以注入LoggerFactory,并选择你的频道

public function acmeAction(LoggerFactory $factory)
{
    $logger = $factory->getLogger('my_channel');
    $logger->log('this is awesome!');
}

7
投票

经过一些搜索后,我发现了一些使用标签的解决方法,并手动将几个参数注入自动服务。

我的回答与@ Thomas-Landauer类似。不同的是,我不必手动创建记录器服务,因为编译器从monolog bundle传递给我做了这个。

services:
    _defaults:
        autowire: true
        autoconfigure: true
    AppBundle\Services\FooService:
        arguments:
            $loggerInterface: '@logger'
        tags:
            - { name: monolog.logger, channel: barchannel }

4
投票

我没有找到一种方法来自动跟踪记录器通道。但是,我找到了原则上使用autowire的方法,并手动注入记录器。有了你的class FooService,这就是services.yml的样子(Symfony 3.3):

# services.yml

services:
    _defaults:
        autowire: true
        autoconfigure: true
    AppBundle\Services\FooService:
        arguments:
            $loggerInterface: '@monolog.logger.barchannel'

因此,“技巧”是明确地注入记录器通道,同时仍然通过自动装配注入此服务的所有其他依赖项。


3
投票

你可以使用bind parameter

services:
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
        public: true
        bind:
            $loggerMyApi: '@monolog.logger.my_api'

然后你可以在服务的构造函数中使用它:

use Psr\Log\LoggerInterface;
...
public function __construct(LoggerInterface $loggerMyApi)
{
...
}

0
投票

基本上,你有两个选择:

首先,服务标记:

services:
App\Log\FooLogger:
    arguments: ['@logger']
    tags:
        - { name: monolog.logger, channel: foo }

然后你可以使用你的CustomLogger作为其他地方的依赖

其次,您可以依靠Monolog为配置中的每个自定义通道自动注册记录器:

# config/packages/prod/monolog.yaml
monolog:
    channels: ['foo', 'bar']

然后,您将获得以下服务:monolog.logger.foo,'monolog.logger.bar'

然后,您可以从服务容器中检索它们,或者手动连接它们,例如:

services:
App\Lib\MyService:
    $fooLogger: ['@monolog.logger.foo']

你可以阅读更多herehere


0
投票

最近我通过MonologBu​​ndle实现了对所有注册记录器的单点访问。而且我也尝试做一些更好的解决方案 - 并且自动生成了记录器装饰器。每个类装饰一个注册的monolog通道的一个对象。

链接到包adrenalinkin/monolog-autowire-bundle

© www.soinside.com 2019 - 2024. All rights reserved.