Kaynağa Gözat

修复 Redis链接异常时日志处理策略与界面显示

ANG YU 5 yıl önce
ebeveyn
işleme
6fee08ecd8
1 değiştirilmiş dosya ile 30 ekleme ve 10 silme
  1. 30 10
      app/Services/LogService.php

+ 30 - 10
app/Services/LogService.php

@@ -5,33 +5,53 @@ namespace App\Services;
 
 
 use App\Log;
+use Exception;
 use Illuminate\Support\Facades\Redis;
 use Illuminate\Support\Facades\Request;
 
 class LogService
 {
-    static public function log($method,$type,$description,$id_user=null){
-        if(!$id_user){
+    static public function log($method, $type, $description, $id_user = null)
+    {
+        if (!$id_user) {
             $id_user = '';
-            $user=auth()->user();
-            if($user) $id_user = $user['id'];
+            $user = auth()->user();
+            if ($user) $id_user = $user['id'];
+        }
+        try {
+            Redis::LLEN('LOGS');
+        } catch (Exception $e) {
+            //redis出现异常直接保存到数据库中
+            (new Log([
+                'operation' => $method,
+                'type' => $type,
+                'description' => $description,
+                'id_user' => $id_user,
+                'ip' => Request::ip(),
+            ]))->save();
         }
         $date = date('Y-m-d H:i:s');
         $log = new Log([
-            'operation'=>$method,
-            'type'=>$type,
-            'description'=>$description,
-            'id_user'=>$id_user,
-            'ip'=>Request::ip(),
+            'operation' => $method,
+            'type' => $type,
+            'description' => $description,
+            'id_user' => $id_user,
+            'ip' => Request::ip(),
             'created_at' => $date,
             '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) {