Creating a Laravel Command to Clear Log Files


 In this tutorial, we’ll create a custom Laravel console command to clean up old log files in the storage/logs directory, while preserving the .gitignore file. This is useful for maintaining a clean server and saving disk space.

Laravel logs application activities in the storage/logs directory. Over time, these logs can accumulate and occupy significant storage space. Deleting these files manually can be tedious, so we'll automate the process with a custom Artisan command.

Steps:

1. Generate the Console Command
Run the following Artisan command to create a new console command:
php artisan make:command ClearLogFiles

2. Edit the Command
Open the generated file located in app/Console/Commands/ClearLogFiles.php.

3. Update the Command Logic
Replace the contents of the file with the following:
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class ClearLogFiles extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'logs:clear';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Clear all log files in storage/logs except .gitignore';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $logPath = storage_path('logs'); // Get the full path to the logs directory

        // Check if the logs directory exists
        if (!is_dir($logPath)) {
            $this->error('The logs directory does not exist.');
            return;
        }

        // Get all files in the logs directory
        $files = File::files($logPath);

        foreach ($files as $file) {
            // Skip the .gitignore file
            if ($file->getFilename() !== '.gitignore') {
                File::delete($file->getPathname()); // Delete the file
            }
        }

        $this->info('Log files cleared successfully, except .gitignore.');
    }
}

4. Register the Command (Optional)
Open app/Console/Kernel.php and add the command to the $commands array:
protected $commands = [
    \App\Console\Commands\ClearLogFiles::class,
];

5. Run the Command
Use the following Artisan command to clear the logs
php artisan logs:clear

Why Preserve .gitignore?

The .gitignore file is essential in projects using Git. It ensures the logs directory is excluded from version control while keeping the folder structure intact. Deleting it may cause unnecessary errors.

This command simplifies log management in your Laravel application, keeping your server clean and efficient.



Previous Post Next Post

نموذج الاتصال