Prechádzať zdrojové kódy

系统异常日志上报

zhaoyang 1 rok pred
rodič
commit
0e2af83887
2 zmenil súbory, kde vykonal 67 pridanie a 1 odobranie
  1. 1 1
      app/Exceptions/Handler.php
  2. 66 0
      app/Libs/Helpers.php

+ 1 - 1
app/Exceptions/Handler.php

@@ -49,7 +49,7 @@ class Handler extends ExceptionHandler
     public function register()
     {
         $this->reportable(function (Throwable $e) {
-            //
+            dingTalkAlertException($e);
         });
     }
 

+ 66 - 0
app/Libs/Helpers.php

@@ -9,6 +9,8 @@ use PhpOffice\PhpSpreadsheet\IOFactory;
 use PhpOffice\PhpSpreadsheet\Spreadsheet;
 use Modules\Common\Support\Trace\CustomizeLogger;
 use PHPMailer\PHPMailer\PHPMailer;
+use Illuminate\Support\Str;
+use Illuminate\Support\Facades\Http;
 
 if(!function_exists("str_decode")){
     /**
@@ -415,3 +417,67 @@ if(!function_exists('getTraceContext')) {
         return app(TraceContext::class);
     }
 }
+
+/**
+ * 钉钉报警
+ *
+ * @param \Throwable $exception
+ * @return void
+ */
+function dingTalkAlertException(\Throwable $exception)
+{
+    $code = $exception->getCode();
+    if($code >0){
+        return ;
+    }
+    $url = 'https://oapi.dingtalk.com/robot/send?access_token=07829435258bf07c5f0b0a0a84c50c4bebc15e585b3040ad43c5e94e213a9bba';
+    $key = 'SEC74f8117d06ae59a7edde24cd9706334dbdd09b5d5734522f060272bdfbfb1abd';
+    $timestamp = time()*1000;
+    $string = $timestamp . "\n" . $key; 
+    $sign = hash_hmac('sha256',$string,$key,true);
+    $sign = urlencode(base64_encode($sign));
+    $url .= '&'.http_build_query(['timestamp'=>$timestamp,'sign'=>$sign]);
+
+    $class_name = get_class($exception);
+    $app_path = app_path();
+    $trace = $exception->getTraceAsString();
+    $trace_list = preg_split('/\n/',$trace);
+    $error = '';
+    foreach($trace_list as $item){
+        if( Str::contains($item,$app_path)){
+            $error .= '- '.trim(preg_replace('/^(\#\d+)/','',$item))."\n";
+        }
+    }
+    $hostname = gethostname();
+
+    $ip = '';
+    $ssh = getenv('SSH_CONNECTION');
+    if($ssh){
+        $ssh_list = explode(' ',$ssh);
+        $ip = isset($ssh_list[2]) ? $ssh_list[2]:'';
+    }
+
+    $result = [
+        'message'=>$exception->getMessage(),
+        'class_name'=>$class_name,
+        'app_path'=>$app_path,
+        'error'=>$error,
+        'hostname'=>$hostname.' - '.$ip
+    ];
+
+    try{
+        $response = Http::post($url,[
+            'msgtype' => 'markdown',
+            'markdown' => [
+                'title'=>basename (base_path()).'异常',
+                'text' => sprintf("### 错误信息: \n%s\n ### 异常详情: \n%s\n### 项目路径: \n%s\n\n ### 主机名:\n%s\n",
+                $result['class_name'].':'.$result['message'],$result['error'],$result['app_path'],$result['hostname'])
+            ]
+        ]);
+    }catch(\Exception $e){
+
+    }
+    
+}
+
+