正如Symfony 3.4所述,由MonologBundle提供的logger
服务和所有其他服务默认设置为私有。[sic]
解决该问题的推荐方法是使用依赖注入。
http://symfony.com/doc/3.4/logging.html
namespace AppBundle\Controller;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction(LoggerInterface $logger)
{
$logger->info('Your Message');
}
}
源代码参考: https://github.com/symfony/monolog-bundle/blob/v3.1.0/Resources/config/monolog.xml#L17
对于服务定义,当启用autowire
时,可以使用依赖注入。[sic]
services:
_defaults:
autowire: true
autoconfigure: true
public: false
AppBundle\:
resource: '../../src/AppBundle/*'
exclude: '../../src/AppBundle/{Entity,Repository,Tests}'
AppBundle\Controller\:
resource: '../../src/AppBundle/Controller'
public: true
tags: ['controller.service_arguments']
然后将依赖注入到服务中,您需要在构造函数的参数中添加类型提示。
namespace AppBundle\Service;
use Psr\Log\LoggerInterface;
class MyService
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
}
如果禁用了{{autowire}},您可以手动定义您的服务来注入日志器别名。
services:
AppBundle\Service\MyService:
arguments: ['@logger']
public: true
或者,为了强制使记录器别名从容器中公开访问,您可以在应用程序服务配置中重新声明服务别名。
services:
logger:
alias: 'monolog.logger'
public: true
除了在配置中覆盖值之外,您还可以将记录器设置为编译器传递中的公共服务。
https://symfony.com/doc/4.4/service_container/compiler_passes.html
Symfony Flex
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
class Kernel extends BaseKernel implements CompilerPassInterface
{
use MicroKernelTrait;
public function process(ContainerBuilder $container)
{
$container->getDefinition('logger')->setPublic(true);
}
}
Symfony捆绑包
namespace AppBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use AppBundle\DependencyInjection\Compiler\CustomPass;
class AppBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new CustomPass());
}
}
namespace AppBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class CustomPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$container->getDefinition('logger')->setPublic(true);
}
}