Joh*_*yce 6 php dependency-injection symfony symfony4
我最近从使用 Symfony 2.7 转向使用 4.2。
以前在我的命令中为了记录到文件,我使用了类似的内容:
$logger = $this->getContainer()->get('logger');
$logger->error('put this in log');
Run Code Online (Sandbox Code Playgroud)
此功能似乎已更改。我可以从控制器登录https://symfony.com/doc/current/logging.html
我可以使用以下命令输出到控制台:
$logger = new ConsoleLogger($output);
$logger->log('error','Put this in the log file');
Run Code Online (Sandbox Code Playgroud)
但尽管我盯着 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
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用Psr\Log\LoggerAwareInterface
(就像使用一样简单Psr\Log\LoggerAwareTrait
)并且记录器将被自动注入(如果可用)。
class FooBar extends Command implements LoggerAwareInterface
{
use LoggerAwareTrait;
// rest of the class implementation
}
Run Code Online (Sandbox Code Playgroud)
这样你甚至不需要使用构造函数注入,因为 Symfony 会自动调用setLogger()
你的命令来为你注入记录器。
您的命令将使用与项目其余部分相同的记录器配置,并且您将立即记录到文件。