命令清除symfony 2中的日志文件



我想知道是否有清除Symfony 2中日志文件的命令?虽然有php app/console cache:clear可以清除缓存,但我不知道有任何命令可以清除日志文件(logs/dev.log和logs/prod.log)。我总是手动清除这些日志。感谢

Symfony中没有显式命令。但是,使用一个空壳班轮并没有什么好羞愧的:

# straightforward …
echo -n '' > app/logs/dev.log
# … or l33t
> app/logs/dev.log # works at least in bash, haven't tried others

对于开发环境,您可以使用

cat /dev/null > app/logs/dev.log

和生产环境

cat /dev/null > app/logs/prod.log

unix系统中的/dev/null是一个虚拟设备(实际上是病毒文件,因为unix中的所有东西都是一个文件),它会丢弃写在上面的所有数据。它也被称为位桶:)

此外,你为什么不考虑利用logrotate
这样,您就可以轻松地分离日志(天、周、月等等),并且永远不会丢失"重要"数据。最后但同样重要的是,您不必手动清除日志文件

这里有一个简单的Symfony命令,用于清除日志,它是为Symfony>2.8编写的。清除整个日志目录的区别/好处在于,它只删除指定环境的日志,而不删除可能添加的自定义日志文件——在我的情况下,这是一项要求。

控制台命令:

namespace StdAppBundleCommand;
use SymfonyComponentFilesystemFilesystem;
use SymfonyComponentConsoleStyleSymfonyStyle;
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;
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));
        }
    }
}

服务配置为:

services:
    std.command.clear_logs_command:
        class: StdAppBundleCommandClearLogsCommand
        arguments: ['%kernel.logs_dir%', '%kernel.environment%']
        tags:
           -  { name: console.command }

执行运行:

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

或者作为要点:[https://gist.github.com/HKandulla/5de5a4074a5296b9465b4825431dfff3#file-clearlogscommand php][1]

最新更新