首页 > 解决方案 > 如何在 Symfony 命令中获取指定通道的记录器?

问题描述

我正在尝试创建一个 symfony 命令,并且我想记录命令执行期间发生的情况。所以我尝试在 monolog.yaml 中创建一个记录器通道:

monolog:
    channels: ['download_site']
    handlers:
        download_site:
            type: stream
            path: "%kernel.logs_dir%/download_site_%kernel.environment%.log"
            level: debug
            channels: ["download_site"]

并进入频道

class DownloadSiteCommand extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $logger = $this->getContainer()->get('monolog.logger.download_site');
    }
}

但是当我执行命令时,错误抛出:

在 DownloadSiteCommand.php 第 31 行:

试图调用“App\Command\Do wnloadSiteCommand”类的名为“getContainer”的未定义方法。

标签: symfony

解决方案


尝试这样的事情

use Psr\Log\LoggerInterface;

class DownloadSiteCommand extends Command
{
    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->logger->info('...');
    }
}

服务.yaml

App\Command\DownloadSiteCommand:
    tags:
        - { 'name': 'monolog.logger', 'channel': 'download_site' }

推荐阅读