Add verbosity to your Symfony2 commands

🦖 This post was published in 2011 and is most likely outdated.

Here is how to use Symfony2’s built-in verbose command line parameter to control verbosity in your commands.

Your need

Let’s say you want a lot of detail when you run a command manually in order to debug or even to see what is happening. But you don’t want so much detail in other situations, for the same command. For instance:

  • this command is made to be used by a cron and you want the output to be logged but you don’t want as much detail as previously in logs
  • if something is wrong you want the command to output about it (and maybe send an email), otherwise you don’t want any output

The solution

Symfony2’s command component has a built-in verbose option for command that you can find with list commande

$ app/console list
Symfony version 2.0.0 - app/dev/debug

Usage:
  [options] command [arguments]

Options:
...
  --verbose        -v Increase verbosity of messages.
...

In your command, just check if the option verbose is given by the user with no need declare it in configure():

if ($input->getOption('verbose')) {
    $output->writeln("blah blah");
}

So you can call your command with the verbose option:

app/console acme:mycommand --verbose

Or even with the shortcut given by Symfony2:

app/console acme:mycommand -v

Comments