如何使用Laravel中的Monolog清除所有日志文件数据

时间:2017-12-22 07:01:09

标签: laravel-5 logfiles

如何在向其添加新内容之前清空日志文件数据。 使用Monolog保存所有日志

  

存储/应用/日志/ *

1 个答案:

答案 0 :(得分:0)

您可以通过ssh使用rm命令删除所有日志:

rm storage/logs/laravel-*.log。如果有后缀,请使用*作为通配符删除所有日志。

或者您只能为app的管理员在Controller方法中添加自定义代码:

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

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

或者创建一个控制台命令。根据版本,5.3以下使用例如:

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

对于5.3及以上版本

php artisan make:command logsClear

如果命令类不存在,则在命令类中添加签名。

protected $signature = 'logs:clear';

在受控制的$ commands数组中的Console / Kernel.php中添加您的类(请注意,您的应用的自定义化后,您的代码会有所不同):

<?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)
        {

        }
    } 

您应该在logsClear类的handle()中添加自定义代码

    <?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);
            }
        }
    }
}

然后运行php artisan logs:clear命令