Laravel 备份日志文件

Laravel 备份日志文件

本文针对的是日志驱动为 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
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'log:backup';

/**
* The console command description.
*
* @var string
*/
protected $description = '日志备份';

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

/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
// 获取驱动类型为 daily 的第一个配置
$config = collect(config('logging.channels'))->where('driver', 'daily')->first();

if(is_null($config)) {
$this->line('读取配置失败');
return 0;
}

// 间隔分钟,24 * 60 则备份上一天
$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

注意:需要与任务调度进行配合实现定时自动备份。

往上