如何在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 "的名为"getContainer"的未定义方法 wnloadSiteCommand".

试试这样的事情

use PsrLogLoggerInterface;
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

AppCommandDownloadSiteCommand:
tags:
- { 'name': 'monolog.logger', 'channel': 'download_site' }

如果要在不自动布线的情况下对记录器使用自定义通道:

/** @var LoggerInterface $logger */
$logger = $this->getContainer()->get('monolog.logger.my_channel');
$logger->warning('Foo');

最新更新