Home » Php » In PHP's Laravel, how do I clear laravel.log?

In PHP's Laravel, how do I clear laravel.log?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m new to Laravel and PHP in general, and I’m trying to clear my errorLog. The current errorlog that I’m using is Laravel’s laravel.log file that is in /app/storage/logs.

Is there an easy way to clear the laravel.log file? Is it safe to delete it and it’ll rebuild when needed?

I’m using the latest version of Ubuntu. Thanks!

How to&Answers:

Echoing an empty string to it would work, like this :

echo "" > storage/logs/laravel.log

The most efficient would be to truncate it to a size of zero :

truncate -s 0 /app/storage/logs/laravel.log

Answer:

Here’s a reusable artisan command that will save you time and effort 🙂

Artisan::command('logs:clear', function() {

    exec('rm ' . storage_path('logs/*.log'));

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

})->describe('Clear log files');

Drop this in routes/console.php then just run php artisan logs:clear

Answer:

Easiest way for me is using vim.

$ vim laravel.log

Then type ggdG

Then :wq save and quit.

Notes:
gg – moves cursor to first line

d – delete

G – to the end of the file

Answer:

Simply just add this line where you want to clear the log.
file_put_contents(storage_path('logs/laravel.log'),'');

Answer:

You can also create custom artisan command.

First, run command php artisan make:command Log/ClearLogFile to create custom command file.

Then, open file on Console/Commands/Log/ClearLogFile.php (depends on you Laravel version, currently I’m using 5.5 version)

After that, you need to define the custom command code, take a look

// Define command name
protected $signature = 'log:clear';

// Add description to your command
protected $description = 'Clear Laravel log';

// Create your own custom command
public function handle(){
    exec('echo "" > ' . storage_path('logs/laravel.log'));
    $this->info('Logs have been cleared');
}

Then, you only need to run just like other php artisan command,

php artisan log:clear

Thanks, for @emotality answer

Answer:

This worked for me :

echo "" > storage/logs/laravel.log

Answer:

For Laravel 5, it would be

truncate -s 0 storage/logs/laravel.log

Answer:

From your Laravel directory:

rm storage/logs/laravel-*.log

Answer:

You can also do: : > storage/logs/laravel.log

Answer:

I usually stick the following line in my controller method when I am running the SQL query listener:

exec("truncate -s 0 " . storage_path('/logs/laravel.log'));

If you use a different monolog channel setup you might want to tweak the name of your log file.

Answer:

I found this solution works well for windows

Artisan::command('logs:clear', function() {
   array_map('unlink', array_filter((array) glob(storage_path('logs/*.log'))));
   $this->comment('Logs have been cleared!');
})->describe('Clear log files');

Run php artisan logs:clear