大多團隊在生產環境下都會關閉app_debug,所以相對應的錯誤信息就不能實時查看到。以下分享一個目前團隊項目正在用的生產環境下相關技術人員能第一時間獲取通知的方法:
先上效果圖:
以上通知是在釘釘中顯示!
下面介紹開發步驟:
1:Thinkphp版本需在5.X或以上,在config/app.php中接管異常處理
(個人案例中調用方式,具體命名依照對應項目建立)
'exception_handle' => '\\app\\Common\\Controller\\Exception',
具體操作可以參考官方文檔:https://www.kancloud.cn/manual/thinkphp5_1/354092
2:在異常接管方法中實現以下代碼
getError(), 422); } // 請求異常 if ($e instanceof HttpException && request()->isAjax()) { return response($e->getMessage(), $e->getStatusCode()); } if ($e->getStatusCode() == 404) { $module = \think\facade\Request::module(); !$module and $module = 'index'; return view($module . '@public/404'); } if ($e->getStatusCode() == 500) { return parent::render($e); } } else { $file = $e->getFile(); $line = $e->getLine(); $code = parent::getCode($e); $message = parent::getMessage($e); $error_message = '[' . $code . '] ErrorException in ' . $file . ' line ' . $line . PHP_EOL . $message; // 此處為釘釘server $server = new \app\Server\DingdingServer(); $data = [ 'text' => ['content' => $error_message] ]; $server->robotSend($data); } // 其他錯誤交給系統處理 return parent::render($e); } }
3:釘釘Server的創建
$msgtype]; $data_string = json_encode($final_data); $webhook = $this->API_URL; $result = $this->request_by_curl($webhook, $data_string); return $result; } protected function request_by_curl($remote_server, $post_string) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $remote_server); 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); $data = curl_exec($ch); curl_close($ch); return $data; } }
此處釘釘接口需要一個access_token參數,具體操作步驟參考:
1:先下載PC版釘釘
2:發起群聊,添加至少2人創建群聊
3:點擊群聊界面右上角三個點中的 群機器人,選擇 添加機器人,選擇最後一個 自定義
4:釘釘API地址就在webhook中
到這裡,生產環境下即使關閉了app_debug,我們也能第一時間收到異常記錄了!特別提醒,釘釘貌似每分鐘只能發送20條推送。
關於釘釘的API,代碼中默認調用text文本形式,其實還有很多,例如 link markdown actionCard 方式,小夥伴們可以自行研究~