Procházet zdrojové kódy

预警信息推送到预警服务平台

kevin_zhangl před 2 roky
rodič
revize
3c8e37676e

+ 2 - 0
common/config/params.php

@@ -332,4 +332,6 @@ return [
         'atUserIds'   => ['rob9muw'],
         'isAtAll'     => false,
     ],
+    // 预警服务平台token
+    'alarmAccessToken' => $mainConfig['alarmAccessToken'],
 ];

+ 63 - 0
common/helpers/Alarm.php

@@ -0,0 +1,63 @@
+<?php
+
+namespace common\helpers;
+
+
+class Alarm
+{
+    // 预警平台Domain
+    private static string $url = 'http://ibs-cn.elken.com:8017';
+
+    // 推送预警信息API
+    private static string $reportApi = '/api/report';
+
+    // 业务环境白名单
+    private static array $allowPlatform = ['fapi.ekhkad.com', 'bapi.ekhkad.com'];
+
+    public static function reportAlarm($message)
+    {
+        // 是否开启预警信息推送
+        $reportAlarmOpen = Cache::getSystemConfig()['reportAlarmOpen']['VALUE'];
+        // 业务平台token
+        $message['platform-id'] = \Yii::$app->params['alarmAccessToken'];
+        // 日志入库
+        Tool::alarmCall($message);
+
+        // 业务环境过滤
+        if ($reportAlarmOpen && (count(self::$allowPlatform) == 0 || in_array($_SERVER['HTTP_HOST'], self::$allowPlatform))) {
+            $result = self::curl(json_encode($message));
+            if ($result['code'] != 200) {
+                // 重新推送一次,如果失败,写错误日志
+                $result = self::curl(json_encode($message));
+                if ($result['code'] != 200) {
+                    LoggerTool::error('预警信息上报平台失败. traceId【' . $message['trace-id'] . '】');
+                }
+            }
+        } else {
+            if ($reportAlarmOpen == '0') {
+                $reason = '上报预警平台状态不允许(reportAlarmOpen=关闭)';
+            } else {
+                $reason = '主机地址不在白名单中(host=' . $_SERVER['HTTP_HOST'] . ')';
+            }
+            LoggerTool::error('预警信息上报平台取消. traceId【' . $message['trace-id'] . '】. 原因:' . $reason);
+        }
+    }
+
+    private static function curl($post_string)
+    {
+        $ch = curl_init();
+        curl_setopt($ch, CURLOPT_URL, self::$url . self::$reportApi);
+        curl_setopt($ch, CURLOPT_POST, 1);
+        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
+        curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
+        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
+        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
+        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
+        $response = curl_exec($ch);
+        curl_close($ch);
+
+        return json_decode($response, true);
+    }
+}

+ 20 - 0
common/helpers/Tool.php

@@ -9,6 +9,7 @@
 namespace common\helpers;
 
 
+use common\models\AlarmCall;
 use Faker\Provider\Uuid;
 use yii\base\Exception;
 use yii\helpers\Url;
@@ -471,4 +472,23 @@ class Tool {
         $uuid = !$upper ? Uuid::uuid() : strtoupper(Uuid::uuid());
         return str_replace('-', $symbol, $uuid);
     }
+
+    /**
+     * 预警日志入库
+     * @param $call
+     * @return void
+     */
+    public static function alarmCall($call)
+    {
+        try {
+            $model = new AlarmCall();
+            $model->trace_id = $call['trace-id'];
+            $model->content = $call;
+            $model->insert();
+        } catch (\yii\mongodb\Exception $e) {
+            LoggerTool::error($call);
+            LoggerTool::error(sprintf('[%s] [%s] [%s]', $e->getFile(), $e->getLine(), $e->getMessage()));
+        } catch (\Exception $e) {
+        }
+    }
 }

+ 67 - 0
common/models/AlarmCall.php

@@ -0,0 +1,67 @@
+<?php
+
+namespace common\models;
+
+use common\components\MongoActiveRecord;
+use Yii;
+use yii\base\InvalidConfigException;
+
+/**
+ * This is the model class for collection "ar_alarm_call".
+ *
+ * @property \MongoDB\BSON\ObjectID|string $_id
+ * @property string $trace_id 堆栈ID
+ * @property mixed $content 内容
+
+ */
+class AlarmCall extends MongoActiveRecord
+{
+    /**
+     * {@inheritdoc}
+     */
+    public static function collectionName()
+    {
+        return 'ar_alarm_call';
+    }
+
+    /**
+     * @return \yii\mongodb\Connection the MongoDB connection used by this AR class.
+     * @throws InvalidConfigException
+     */
+    public static function getDb()
+    {
+        return Yii::$app->get('dbLog');
+    }
+
+    /**
+     * 获取id
+     * @return string
+     */
+    public function getId() {
+        return (string) $this->_id;
+    }
+    /**
+     * {@inheritdoc}
+     */
+    public function attributes()
+    {
+        return [
+            '_id',
+            'trace_id',
+            'content',
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            '_id' => 'objectID',
+            'trace_id' => 'trace_id',
+            'content' => 'content',
+        ];
+    }
+
+}

+ 3 - 1
composer.json

@@ -23,7 +23,9 @@
         "anlity/yii2-swoole-async-timer": "^0.9.1",
         "yiisoft/yii2-mongodb": "^2.1",
         "godruoyi/php-snowflake": "^1.0",
-        "yiisoft/yii2-redis": "^2.0"
+        "yiisoft/yii2-redis": "^2.0",
+	    "ext-json": "*",
+	    "ext-curl": "*"
     },
     "require-dev": {
         "yiisoft/yii2-debug": "~2.0.0",

+ 6 - 4
vendor/yiisoft/yii2/web/ErrorHandler.php

@@ -7,6 +7,7 @@
 
 namespace yii\web;
 
+use common\helpers\Alarm;
 use common\helpers\DingTalk;
 use common\helpers\LoggerTool;
 use common\helpers\Tool;
@@ -178,12 +179,13 @@ class ErrorHandler extends \yii\base\ErrorHandler
 
                 // 错误日志写入
                 $it['trace-id'] = Tool::generateId();
-                LoggerTool::error($it);
-
+//                LoggerTool::error($it);
+                // 推送消息到预警平台
+                Alarm::reportAlarm($it);
                 // 提醒只报出基本错误
-                unset($it['stack-trace']);
+//                unset($it['stack-trace']);
                 // 发送钉钉提醒
-                DingTalk::sendNotice($it);
+//                DingTalk::sendNotice($it);
 
                 $array = [
                     'name' => ($exception instanceof Exception || $exception instanceof ErrorException) ? $exception->getName() : 'Exception',