如何在 Symfony 4 的控制台命令中使用记录器?
How to use the logger in a console command on Symfony 4?
我最近从使用 Symfony 2.7 到 4.2。
之前在我的命令中为了记录到一个文件我使用了类似的东西:
$logger = $this->getContainer()->get('logger');
$logger->error('put this in log');
此功能似乎已更改。我可以从 https://symfony.com/doc/current/logging.html
之后的控制器登录
我可以输出到控制台使用:
$logger = new ConsoleLogger($output);
$logger->log('error','Put this in the log file');
但是尽管我一直盯着 symfony 网站上的信息看,但我还是想不通如何使用 symfony 4.2 从命令中登录到文件。
您需要将记录器注入您的命令,就像在控制器示例中显示的那样。
class ExampleCommand extends Command {
protected static $defaultName = 'do:something:awesome';
/**
* @var \Psr\Log\LoggerInterface
*/
private $logger;
public function __construct( LoggerInterface $logger ) {
$this->$logger = $logger;
parent::__construct( );
}
public function execute( InputInterface $input, OutputInterface $output ) {
$io = new SymfonyStyle( $input, $output );
$this->logger->info('Logging like a boss at ' . __FILE__ . ':' . __LINE__);
// the rest of your command
}
您也可以使用 Psr\Log\LoggerAwareInterface
(与使用 Psr\Log\LoggerAwareTrait
一样简单),如果可用,记录器将自动注入。
class FooBar extends Command implements LoggerAwareInterface
{
use LoggerAwareTrait;
// rest of the class implementation
}
有了这个你甚至不需要使用构造函数注入,因为 Symfony 会在你的命令上自动调用 setLogger()
来为你注入记录器。
您的命令将使用与项目其余部分相同的记录器配置,您将立即记录到文件。
我最近从使用 Symfony 2.7 到 4.2。
之前在我的命令中为了记录到一个文件我使用了类似的东西:
$logger = $this->getContainer()->get('logger');
$logger->error('put this in log');
此功能似乎已更改。我可以从 https://symfony.com/doc/current/logging.html
之后的控制器登录我可以输出到控制台使用:
$logger = new ConsoleLogger($output);
$logger->log('error','Put this in the log file');
但是尽管我一直盯着 symfony 网站上的信息看,但我还是想不通如何使用 symfony 4.2 从命令中登录到文件。
您需要将记录器注入您的命令,就像在控制器示例中显示的那样。
class ExampleCommand extends Command {
protected static $defaultName = 'do:something:awesome';
/**
* @var \Psr\Log\LoggerInterface
*/
private $logger;
public function __construct( LoggerInterface $logger ) {
$this->$logger = $logger;
parent::__construct( );
}
public function execute( InputInterface $input, OutputInterface $output ) {
$io = new SymfonyStyle( $input, $output );
$this->logger->info('Logging like a boss at ' . __FILE__ . ':' . __LINE__);
// the rest of your command
}
您也可以使用 Psr\Log\LoggerAwareInterface
(与使用 Psr\Log\LoggerAwareTrait
一样简单),如果可用,记录器将自动注入。
class FooBar extends Command implements LoggerAwareInterface
{
use LoggerAwareTrait;
// rest of the class implementation
}
有了这个你甚至不需要使用构造函数注入,因为 Symfony 会在你的命令上自动调用 setLogger()
来为你注入记录器。
您的命令将使用与项目其余部分相同的记录器配置,您将立即记录到文件。