Log All Executed Console Commands to File in Symfony 8

Log All Executed Console Commands to File in Symfony 8

Symfony offers an event-driven Console component that makes it possible to react to command execution. Every time a console command runs, specific events are dispatched. By listening to these events, additional logic such as logging can be attached without modifying individual commands. Recording every executed console command into a log file can help with debugging, auditing, or monitoring application behavior in development and production environments. This tutorial demonstrates how to log all executed console commands to file in Symfony 8 application.

Right before any command is executed, the ConsoleEvents::COMMAND event is triggered. Listeners and subscribers receive a ConsoleCommandEvent instance, which provides access to the command object, the input options and arguments.

For example, to log command activity, an event subscriber can be created that listens to this event and writes details to the application logger:

src/EventSubscriber/ConsoleCommandSubscriber.php

<?php

namespace App\EventSubscriber;

use Psr\Log\LoggerInterface;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ConsoleCommandSubscriber implements EventSubscriberInterface
{
    public function __construct(private LoggerInterface $logger)
    {
    }

    public static function getSubscribedEvents(): array
    {
        return [ConsoleEvents::COMMAND => 'onConsoleCommand'];
    }

    public function onConsoleCommand(ConsoleCommandEvent $event): void
    {
        $command = $event->getCommand();
        $input = $event->getInput();

        $this->logger->info(
            'Command',
            [
                'name' => $command?->getName(),
                'inputs' => $input->getRawTokens(true),
            ],
        );
    }
}

For testing purposes, run the following command:

php bin/console debug:container --deprecations

When this command runs, the subscriber automatically logs its details. By default, in the development environment, entries appear in the var/log/dev.log file. Example log output:

[2026-02-18T12:44:31.804009+00:00] app.INFO: Command {"name":"debug:container","inputs":["--deprecations"]} []

Leave a Comment

Cancel reply

Your email address will not be published.