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 (empty($arr)) { return; } $description = (is_string($arr->description) ? $arr->description : json_encode($arr->description)) ?? ''; //当前日志超长,跳过该条,不插入 if (strlen($description)> 1024 * 512) { continue; } if ($length + strlen($description) > 1024 * 512) { Log::query()->insert($data); $length = 0; $data = []; } $length = $length + strlen($description); $data[] = [ 'class' => $arr->class, 'id_user' => $arr->id_user, 'ip' => $arr->ip, 'method' => $arr->method, 'description' => $description, 'created_at' => $arr->created_at, 'updated_at' => $arr->updated_at, ]; } if ($data) { Log::query()->insert($data); } } }