Skip to content

Instantly share code, notes, and snippets.

@grambas
Created January 18, 2024 07:47
Show Gist options
  • Select an option

  • Save grambas/aada03dac826b5be1afa8ee4d4dbe687 to your computer and use it in GitHub Desktop.

Select an option

Save grambas/aada03dac826b5be1afa8ee4d4dbe687 to your computer and use it in GitHub Desktop.

Revisions

  1. grambas created this gist Jan 18, 2024.
    65 changes: 65 additions & 0 deletions TestLoggingCommand.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,65 @@
    <?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;
    }
    }