Skip to content

Instantly share code, notes, and snippets.

@HKandulla
Last active May 27, 2021 06:49
Show Gist options
  • Save HKandulla/5de5a4074a5296b9465b4825431dfff3 to your computer and use it in GitHub Desktop.
Save HKandulla/5de5a4074a5296b9465b4825431dfff3 to your computer and use it in GitHub Desktop.
Symfony Clear Logs Command
<?php
namespace Std\AppBundle\Command;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ClearLogsCommand extends Command
{
/**
* @var SymfonyStyle
*/
private $io;
/**
* @var Filesystem
*/
private $fs;
private $logsDir;
private $env;
/**
* ClearLogsCommand constructor.
*
* @param null|string $logsDir
* @param $env
*/
public function __construct($logsDir, $env)
{
parent::__construct();
$this->logsDir = $logsDir;
$this->env = $env;
}
/**
* @inheritdoc
*/
protected function configure()
{
$this
->setName('std:logs:clear')
->setDescription('Deletes all logfiles');
}
/**
* @param InputInterface $input
* @param OutputInterface $output
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->io = new SymfonyStyle($input, $output);
$this->fs = new Filesystem();
$log = $this->logsDir . '/' . $this->env . '.log';
$this->io->comment(sprintf('Clearing the logs for the <info>%s</info> environment', $this->env));
$this->fs->remove($log);
if (!$this->fs->exists($log)) {
$this->io->success(sprintf('Logs for the "%s" environment was successfully cleared.', $this->env));
} else {
$this->io->error(sprintf('Logs for the "%s" environment could not be cleared.', $this->env));
}
}
}
@HKandulla
Copy link
Author

HKandulla commented Aug 4, 2016

The service config would be:

services:
    std.command.clear_logs_command:
        class: Std\AppBundle\Command\ClearLogsCommand
        arguments: ['%kernel.logs_dir%', '%kernel.environment%']
        tags:
           -  { name: console.command }

To execute run:

app/console std:logs:clear --env=prod

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment