How to clear all Log files data using Monolog in Laravel

3.8k Views Asked by At

How to empty log files data before adding new contents to it. Using Monolog for saving all logs inside

storage/app/logs/*

1

There are 1 best solutions below

2
Nikola Kirincic On

You can use rm command through ssh to remove all logs:

rm storage/logs/laravel-*.log. Use * as wildcard to remove all logs if they have suffixes.

Or you can add custom code within Controller method only for admins of app:

 $files = glob('storage/logs/laravel*.log');

        foreach($files as $file){
            if(file_exists($file)){
                unlink($file);
            }
        }

Or create a console command. Depending on version, below 5.3 use for example:

php artisan make:console logsClear --command=logs:clear

For versions 5.3 and above

php artisan make:command logsClear

add signature within command class if it doesn't exist.

protected $signature = 'logs:clear';

Add your class in Console/Kernel.php, in protected $commands array ( note that your code varies upon customization for your app):

<?php

    namespace App\Console;


    use App\Console\Commands\logsClear;
    use Illuminate\Console\Scheduling\Schedule;
    use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

    use App\Utils\ShareHelper;

    class Kernel extends ConsoleKernel
    {
        /**
         * The Artisan commands provided by your application.
         *
         * @var array
         */
        protected $commands = [


            logsClear::class,

        ];

        /**
         * Define the application's command schedule.
         *
         * @param  \Illuminate\Console\Scheduling\Schedule $schedule
         * @return void
         */
        protected function schedule(Schedule $schedule)
        {

        }
    } 

You should add then custom code in handle() of logsClear class

    <?php

    namespace App\Console\Commands;

    use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $files = glob('storage/logs/laravel*.log');

        foreach($files as $file){
            if(file_exists($file)){
                unlink($file);
            }
        }
    }
}

Then run php artisan logs:clear command