Skip to content

Instantly share code, notes, and snippets.

@grambas
Created January 18, 2024 07:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grambas/aada03dac826b5be1afa8ee4d4dbe687 to your computer and use it in GitHub Desktop.
Save grambas/aada03dac826b5be1afa8ee4d4dbe687 to your computer and use it in GitHub Desktop.
Test symfony logging with command
<?php
declare(strict_types=1);
namespace App\Command;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
final class LoggerCommand extends ContainerAwareCommand
{
protected static $defaultName = 'logger:log';
/** @var SymfonyStyle */
protected $io;
protected $logger;
public function __construct(LoggerInterface $logger)
{
parent::__construct();
$this->logger = $logger;
$this->setDescription('Log message. Log level, message and context can be set');
}
public function execute(InputInterface $input, OutputInterface $output): void
{
$logLevel = $this->io->choice('Select log level', array_keys(Logger::getLevels()));
$message = $this->io->ask('Enter log message', 'test log message', static function ($message) {
if (empty($message)) {
throw new RuntimeException('Message can not be empty');
}
return $message;
});
$context = [];
$add = $this->io->confirm('Add context?');
while ($add) {
$this->addContext($context);
$add = $this->io->confirm('Add context?');
}
$this->logger->log($logLevel, $message, $context);
$this->io->success('message logged');
}
protected function initialize(InputInterface $input, OutputInterface $output): void
{
$this->io = new SymfonyStyle($input, $output);
}
private function addContext(array &$context): void
{
$key = $this->io->ask('enter context key', '');
$value = $this->io->ask('enter context value', '');
$context[$key] = $value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment