How to PROPERLY clean Laravel logs? [SOLVED]


Written by - Steve Alila
Reviewed by - Deepak Prasad

Different methods to clean Laravel logs

There are several methods to clean Laravel logs, depending on the specific logs you want to clean and how you want to do it. Here are some common methods:

  1. Manual deletion: You can manually delete the log files in the storage/logs directory. This is a quick and easy method, but it's not automated and can lead to issues if you accidentally delete important logs.
  2. Logrotate: You can use the logrotate utility to automatically rotate log files and keep them at a manageable size. Logrotate can be configured to compress and/or delete old log files based on a variety of criteria, such as file size or age.
  3. Daily log pruning: Laravel provides a robust scheduling system that can be leveraged to create a custom log pruning feature. This allows you to automatically clear old log files on a daily basis. To add this functionality, first create a custom artisan command (e.g., log:clear) that handles the pruning logic. Once you've created and tested this command, you can schedule it to run daily by adding the following line to your app/Console/Kernel.php file:
$schedule->command('log:clear')->daily();

This will run the log:clear Artisan command once a day, which will delete all log files that are older than the specified number of days (by default, 5 days).

  1. Custom log pruning: You can create a custom command to prune logs based on your own criteria. For example, you could delete logs that are older than a certain number of days, or delete logs that have a certain filename or extension. You can then add this command to your app/Console/Kernel.php file and schedule it to run on a regular basis.

Method-1: Manual deletion

Manually clean log files

The simplest way to clean Laravel logs is to echo nothing in the log file.

Input

cat storage/logs/laravel.log | wc -l
echo "" > storage/logs/laravel.log
cat storage/logs/laravel.log | wc -l

Output

steve@thisHostname:~/lara_app$ cat storage/logs/laravel.log | wc -l
52
steve@thisHostname:~/lara_app$ echo "" > storage/logs/laravel.log
steve@thisHostname:~/lara_app$ cat storage/logs/laravel.log | wc -l
1

The log file now has 1 line holding an empty space.

 

Truncate the file to a size of zero

Let's clean the logs by truncating the file to a size of zero 0.

Input

cat storage/logs/laravel.log | wc -l
truncate -s 0 storage/logs/laravel.log
cat storage/logs/laravel.log | wc -l

Output

steve@thisHostname:~/lara_app$ cat storage/logs/laravel.log | wc -l
50
steve@thisHostname:~/lara_app$ truncate -s 0 storage/logs/laravel.log
steve@thisHostname:~/lara_app$ cat storage/logs/laravel.log | wc -l
0

 

Use vim key bindings

You can also open the logs file in a text editor, manually select all lines, and delete them. For instance, let's open the file in vim.

vim storage/logs/laravel.log

Select and delete all the lines using the following key bindings ggdG, where (in normal mode) gg moves the cursor to the first line and d deletes the lines to the end of the file G. Lastly, save and quit the updated file :wq.

Output

steve@thisHostname:~/lara_app$ cat storage/logs/laravel.log | wc -l
49
steve@thisHostname:~/lara_app$ vim storage/logs/laravel.log 
steve@thisHostname:~/lara_app$ cat storage/logs/laravel.log | wc -l
0

 

Use the rm command

Additionally, you can clean Laravel logs by removing the log file.

Input

cat storage/logs/laravel.log | wc -l
rm storage/logs/laravel.log
ls storage/logs/

Output

steve@thisHostname:~/lara_app$ cat storage/logs/laravel.log | wc -l
49
steve@thisHostname:~/lara_app$ rm storage/logs/laravel.log
steve@thisHostname:~/lara_app$ ls storage/logs/
steve@thisHostname:~/lara_app$

How to PROPERLY clean Laravel logs? [SOLVED]

 

Method-2: Create log cleaning function

Let's write a custom log-cleaning function in the routes/console.php.

// location: routes/console.php
// run: php artisan logs:clean

artisan::command('logs:clean', function() {
    
    exec('rm -f ' . storage_path('logs/*.log'));
    exec('rm -f ' . base_path('*.log'));
    $this->comment('Logs cleaned!');
    
})->describe('Clean the log files');

The callback function removes all files ending in .logthen leaves a message Logs cleaned!

Clean Laravel logs

Here is a replica of the command in Windows.

// location: routes/console.php
// run: php artisan logs:clean

artisan::command('logs:clean', function() {
   array_map('unlink', array_filter((array) glob(storage_path('logs/*.log'))));
   $this->comment('Logs cleaned!');
})->describe('Clean the log files');

How to PROPERLY clean Laravel logs? [SOLVED]

Apart from writing a custom artisan command, you can automate the process with packages like logcleaner .

 

Method-3: Custom Log Pruning

To create a custom command to prune logs based on your own criteria, you can follow these steps:

Create a new command using the php artisan make:command command. For example, to create a command called log:prune, run:

php artisan make:command log:prune

Open the new app/Console/Commands/LogPrune.php file that was generated and add the following code to the handle method:

use Illuminate\Support\Facades\File;

public function handle()
{
    $logPath = storage_path('logs/');
    $files = File::glob($logPath . '*.log');

    foreach ($files as $file) {
        $lastModified = File::lastModified($file);
        $daysOld = floor((time() - $lastModified) / (60 * 60 * 24));

        if ($daysOld > 7) {
            File::delete($file);
        }
    }
}

This code gets a list of all log files in the storage/logs directory, calculates how many days old each file is, and deletes any files that are older than 7 days.

Add the new command to the $commands array in the app/Console/Kernel.php file:

protected $commands = [
    Commands\LogPrune::class,
];

Schedule the command to run on a regular basis using Laravel's scheduler. For example, to run the command once a week on Sundays at midnight, add the following line to the schedule method in Kernel.php:

$schedule->command('log:prune')->weeklyOn(0, '0:00');

 

Method-4: Daily Log Pruning

You can create a custom artisan command to clear your logs and then schedule that command to run daily. Below is a basic outline of how you might do that:

Create a new command with php artisan make:command ClearLog.

Open the new command file located in app/Console/Commands/ClearLog.php.

In the handle() method, add the logic to clear the log. This might look something like:

public function handle()
{
    $file = storage_path('logs/laravel.log');

    if (file_exists($file)) {
        // Clear the log.
        file_put_contents($file, '');
    }

    $this->info('Logs have been cleared');

    return 0;
}

In your Kernel.php file located in app/Console/, add your new command to the schedule. This might look something like:

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

Remember to replace 'log:clear' with whatever you name your command.

 

Conclusion

In summary, cleaning Laravel logs is an important task that helps keep your application running smoothly and prevents log files from becoming too large and unmanageable. There are several methods you can use to clean logs, including manual deletion, logrotate, daily log pruning, and custom log pruning.

Manual deletion is a quick and easy method but requires manual intervention and may lead to issues if important logs are accidentally deleted. Logrotate is a useful tool that can be configured to automatically rotate logs and delete old files based on various criteria.

Laravel provides a built-in command for daily log pruning that can be scheduled to run automatically using the Laravel scheduler. Additionally, you can create a custom command to prune logs based on your own criteria and schedule it to run on a regular basis.

The best method for cleaning logs in your application will depend on your specific needs and the size and complexity of your log files. By regularly cleaning your logs, you can ensure that your application remains efficient and easy to manage.

 

Views: 4

Steve Alila

He specializes in web design, WordPress development, and data analysis, with proficiency in Python, JavaScript, and data extraction tools. Additionally, he excels in web API development, AI integration, and data presentation using Matplotlib and Plotly. You can connect with him on LinkedIn or check his projects on GitHub page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

2 thoughts on “How to PROPERLY clean Laravel logs? [SOLVED]”

  1. “Daily log pruning: Laravel has a built-in feature that allows you to prune old log files on a daily basis. To use this feature, add the following line to your app/Console/Kernel.php file:”

    This is not built-in. You literally describe how you create the command yourself later in the article.

    Reply

Leave a Comment