Skip to main content

Clearing Laravel Log Files - Step-by-Step Guide

Introduction:
In this document, we will learn how to clear Laravel log files to manage disk space efficiently and keep log files organized. Laravel logs essential information about application errors, queries, and other critical events. Over time, log files can consume significant disk space, affecting server performance. Clearing log files periodically is a good practice to maintain a healthy Laravel application.

Prerequisites:
Before proceeding with the steps, ensure you have the following:

A Laravel project set up on your development environment.
Basic knowledge of the Laravel framework and its directory structure.
Command Line Interface (CLI) access to run Artisan commands.
Step 1: Understanding Laravel Log Files
Laravel logs are stored in the "storage/logs" directory of your Laravel project. Log files are named with the "laravel.log" prefix and a date suffix, such as "laravel-2023-05-25.log".

Step 2: Viewing Log Files
To see the contents of the log file, open the terminal or command prompt, navigate to your Laravel project's root directory, and use the following command:

cat storage/logs/laravel.log


Step 3: Clearing the Log Files
Laravel provides an Artisan command to clear the log files. To clear the log files, run the following command:

php artisan log:clear


This command will remove all log files from the "storage/logs" directory, keeping the "laravel.log" file empty.

Step 4: Scheduling Log Clearing
To automate the log clearing process, you can add the "log:clear" command to the Laravel task scheduler. Open the "App\Console\Kernel.php" file, and in the "schedule" method, add the following code:

 

protected function schedule(Schedule $schedule){
  $schedule->command('log:clear')->daily();
}


The above code schedules the log clearing command to run daily. You can modify the frequency as per your requirement.

Step 5: Running the Scheduler
To activate the task scheduler, you need to add a cron entry that calls the Laravel scheduler every minute. Open the terminal or command prompt and type:

crontab -e


Add the following line at the end of the file:

* * * * * cd /path/to/your/laravel/project && php artisan schedule:run >> /dev/null 2>&1

Save the file and exit. This cron job will run every minute, and the Laravel scheduler will take care of clearing the log files daily.

Conclusion:
In this guide, we learned how to clear Laravel log files manually using the "log:clear" Artisan command and how to automate this process by scheduling it with the Laravel task scheduler. Regularly clearing log files will help maintain disk space and ensure the smooth functioning of your Laravel application.