本文针对的是日志驱动为 daily 。
创建命令行
1
| $ php artisan make:command LogBackup
|
app\Console\Commands\LogBackup.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| <?php
namespace App\Console\Commands;
use Monolog\Handler\RotatingFileHandler; use Illuminate\Http\File; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Route; use Illuminate\Console\Command;
class LogBackup extends Command {
protected $signature = 'log:backup';
protected $description = '日志备份';
public function __construct() { parent::__construct(); }
public function handle() { $config = collect(config('logging.channels'))->where('driver', 'daily')->first();
if(is_null($config)) { $this->line('读取配置失败'); return 0; }
$interval_minute = 24 * 60;
$pathinfo = pathinfo($config['path']);
$filename = $pathinfo['filename'] . '-' . now()->subMinutes($interval_minute)->format(RotatingFileHandler::FILE_PER_DAY); $filepath = $pathinfo['dirname'] . DIRECTORY_SEPARATOR . $filename . '.' . $pathinfo['extension'];
if(!is_file($filepath)) { $this->line('文件不存在'); return 0; }
$app_name = config('app.name');
$disk = Storage::disk('oss');
$storage_path = $app_name . '/log_backup/' . $filename . '.' . $pathinfo['extension'];
if($disk->exists($storage_path)) { $storage_size = $disk->size($storage_path);
if($storage_size && $storage_size >= filesize($filepath)) { $this->line('当前文件大小未超过已上传的文件'); return 0; } }
$disk->put($storage_path, file_get_contents($filepath));
$this->info('上传成功'); return 1; } }
|
执行
1
| $ php artisan log:backup
|
注意:需要与任务调度进行配合实现定时自动备份。