Control Verbosity Level for Console Command in Symfony 7

Control Verbosity Level for Console Command in Symfony 7

Symfony provides a Console component for creating command line applications. When building console commands, it's essential to consider the verbosity level, which determines the amount of information displayed during command execution. Symfony allows developers to control the verbosity level, tailoring the output to meet different needs, from basic information to detailed debugging. This tutorial explains how to control verbosity level for console command in Symfony 7.

Symfony provides several verbosity levels that can be adjusted to control the amount of information displayed on the console.

Verbosity level can be controlled by -q and -v options, or by setting the SHELL_VERBOSITY environment variable to control verbosity level globally for all commands. Note that the -q and -v options take precedence over the value of SHELL_VERBOSITY.

Console optionSHELL_VERBOSITY valuePHP constant
-q or --quiet-1OutputInterface::VERBOSITY_QUIET
(none)0OutputInterface::VERBOSITY_NORMAL
-v1OutputInterface::VERBOSITY_VERBOSE
-vv2OutputInterface::VERBOSITY_VERY_VERBOSE
-vvv3OutputInterface::VERBOSITY_DEBUG

You can display a message in a command based on a particular verbosity level. For instance:

<?php

namespace App\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'app:test')]
class TestCommand extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $output->writeln('Normal verbosity');
        $output->writeln('Normal verbosity', OutputInterface::VERBOSITY_NORMAL);
        $output->writeln('Verbose -v', OutputInterface::VERBOSITY_VERBOSE);
        $output->writeln('Very verbose -vv', OutputInterface::VERBOSITY_VERY_VERBOSE);
        $output->writeln('Debug -vvv', OutputInterface::VERBOSITY_DEBUG);

        return Command::SUCCESS;
    }
}

We can control verbosity level as follows:

CommandOutput
php bin/console app:test -q(No output)
php bin/console app:testNormal verbosity
Normal verbosity
php bin/console app:test -vNormal verbosity
Normal verbosity
Verbose -v
php bin/console app:test -vvNormal verbosity
Normal verbosity
Verbose -v
Very verbose -vv
php bin/console app:test -vvvNormal verbosity
Normal verbosity
Verbose -v
Very verbose -vv
Debug -vvv

Leave a Comment

Cancel reply

Your email address will not be published.