| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- <?php
- namespace App\Services;
- use App\Log;
- use Exception;
- use Illuminate\Support\Facades\Redis;
- use App\Traits\ServiceAppAop;
- class LogService
- {
- use ServiceAppAop;
- static public function log($class, $method, $description, $id_user = null,$type='log')
- {
- if (!$id_user) {
- $id_user = '';
- $user = auth()->user();
- if ($user) $id_user = $user['id'];
- }
- $log=new Log([
- 'class' => $class,
- 'method' => $method,
- 'description' => $description,
- 'id_user' => $id_user,
- 'ip' => request()->ip(),
- 'type' => $type,
- ]);
- try {
- Redis::LLEN('LOGS');
- } catch (Exception $e) {
- //redis出现异常直接保存到数据库中
- $log->save();
- return;
- }
- $date = date('Y-m-d H:i:s');
- $log['created_at']=$date;
- $log['updated_at']=$date;
- Redis::LPUSH('LOGS', $log);
- }
- public static function syncRedisLogs()
- {
- try {
- Redis::LLEN('LOGS');
- } catch (Exception $e) {
- session()->flash('danger', 'Redis服务异常无法正常同步,最新日志已直接保存到数据库中,但已缓存的日志无法同步,请检查Redis是否正常,然后再尝试同步');
- return;
- }
- $data = [];
- $length = 0;
- while (Redis::LLEN('LOGS') > 0) {
- $log = Redis::LPOP('LOGS');
- $arr = json_decode($log);
- if ($length + strlen($arr->description) > 1024 * 512) {
- Log::query()->insert($data);
- $length = 0;
- $data = [];
- }
- $length = $length + strlen($arr->description);
- $data[] = [
- 'class' => $arr->class,
- 'id_user' => $arr->id_user,
- 'ip' => $arr->ip,
- 'method' => $arr->method,
- 'description' => $arr->description,
- 'created_at' => $arr->created_at,
- 'updated_at' => $arr->updated_at,
- ];
- }
- if ($data) {
- Log::query()->insert($data);
- }
- }
- }
|