如何配置 Monolog 以显示控制台消息
可以使用控制台,根据特定的详细级别打印消息,通过在命令运行时传递的 OutputInterface 实例来实现。
当需要进行大量日志记录时,根据详细级别设置 (-v
, -vv
, -vvv
) 打印信息会很麻烦,因为调用需要包装在条件语句中。例如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
protected function execute(InputInterface $input, OutputInterface $output): int
{
if ($output->isDebug()) {
$output->writeln('Some info');
}
if ($output->isVerbose()) {
$output->writeln('Some more info');
}
// ...
}
MonologBridge 提供了一个 ConsoleHandler,它监听控制台事件,并根据当前的日志级别和控制台详细程度,将日志消息写入控制台输出,而无需使用这些语义方法来测试每个详细级别。
上面的示例可以重写为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// src/Command/YourCommand.php
namespace App\Command;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class YourCommand extends Command
{
public function __construct(
private LoggerInterface $logger,
) {
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->logger->debug('Some info');
$this->logger->notice('Some more info');
return Command::SUCCESS;
}
}
根据命令运行的详细级别和用户配置(见下文),这些消息可能会或可能不会显示在控制台上。如果显示,它们会带有时间戳并被适当着色。此外,错误日志会被写入错误输出 (php://stderr
)。不再需要有条件地处理详细级别设置。
LoggerInterface | 详细程度 | 命令行 |
---|---|---|
->error() | OutputInterface::VERBOSITY_QUIET | stderr |
->warning() | OutputInterface::VERBOSITY_NORMAL | stdout |
->notice() | OutputInterface::VERBOSITY_VERBOSE | -v |
->info() | OutputInterface::VERBOSITY_VERY_VERBOSE | -vv |
->debug() | OutputInterface::VERBOSITY_DEBUG | -vvv |
Monolog 控制台处理器默认启用
1 2 3 4 5 6 7 8 9 10 11 12
# config/packages/dev/monolog.yaml
monolog:
handlers:
# ...
console:
type: console
process_psr_3_messages: false
channels: ['!event', '!doctrine', '!console']
# optionally configure the mapping between verbosity levels and log levels
# verbosity_levels:
# VERBOSITY_NORMAL: NOTICE
现在,日志消息将根据日志级别和详细程度显示在控制台上。默认情况下(正常详细程度级别),将显示警告及更高级别的消息。但在完全详细模式下,将显示所有消息。
这项工作,包括代码示例,根据 Creative Commons BY-SA 3.0 许可证获得许可。