使用場景,服務器報異常錯誤,想要及時收到報警信息並處理
環境介紹,本博使用yaf框架+php,僅僅提供思路,參考,具體根據自己實際情況進行編寫
1,每十分鍾執行一次任務腳本
# 每10分鍾執行一次的任務
if [ "0" -eq "$(($minute % 10))" ]; then
php -f ${pathRoot}public/index.php 'request_uri=/error/dingdingLog'
fi
2,先在釘釘pc端創建業務機器人
具體操作,參考:https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
我使用的是第三種方式,ip段
3,如果是已添加之后,復制鏈接
這是你需要群發消息的地址
https://oapi.dingtalk.com/robot/send?access_token=XXXXXX
4,php實現,捕獲接口異常
/**
* error action
*
* @return bool
* @throws Exception
*/
public function errorAction()
{
$req = $this->getRequest();
$exception = $req->getException();
//來自接口的錯誤
if ($exception instanceof ApiException) {
return $this->json($exception->getCode(), $exception->getMessage());
}
//其它異常
if ($this->yafAutoRender) {
$exceptions = [];
if (! $exception instanceof Exception) {
$exception = new Yaf\Exception\LoadFailed('no exception');
}
//add exception
$exceptions[] = $exception;
//show trace
$this->getView()->exceptions = $exceptions;
Yaf\Dispatcher::getInstance()->autoRender(true);
} else {
if ($exception instanceof Yaf\Exception\LoadFailed) { //接口不存在
$this->log($exception, ApiException::NOT_EXISTS);
return $this->json(ApiException::NOT_EXISTS, $exception->getMessage());
}
$this->log($exception);
return $this->json(ApiException::FATAL, $exception->getMessage());
}
}
5,修改框架錯誤日志log寫入方法
/**
* error log
*
* @param Exception $exception
* @param int $error_code 0-正常報錯
*/
private function log($exception, $error_code = 0)
{
//log exception
$msg = sprintf("%s:%s. in %s on line %s, trace:%s",
get_class($exception),
$exception->getMessage(),
$exception->getFile(),
$exception->getLine(),
$exception->getTraceAsString()
);
// 排除 404 的報錯才推送
// there is not method / not such file or diractory
if ($error_code != ApiException::NOT_EXISTS) {
$this->saveLog($exception->getMessage());
}
LK::log()->error($msg);
}
如上所示,我將一部分日志寫入redis
6,保存日志
public function saveLog($msg)
{
$redis = LK::redis('log');
$key = md5($msg);
$saved = $redis->sadd('error_log', $key);
if ($saved) {
$redis->setex($key, 1100, $msg);
}
return $saved;
}
7,讀取redis消息,給釘釘推送錯誤消息
public function dingdingLogAction()
{
$redis = LK::redis('log');
$keys = $redis->sMembers('error_log');
if (count($keys)) {
foreach ($keys as $key) {
if (false != ($msg = $redis->get($key))) {
Func::dingdingLog($msg);
}
}
$redis->del('error_log');
}
}
8,curl上面那個地址,具體信息自行修改
/**
* 釘釘消息推送
* 推到釘釘 php+web 群
* @return bool
*/
public static function dingdingLog($msg)
{
$url = 'https://oapi.dingtalk.com/robot/send?access_token=XXXXXX';
$env = \Yaf\Application::app()->environ();
$fix = 'somi';
$time = date('Y-m-d H:i:s');
$data = [
'msgtype' => 'text',
'text' => [
'content' => "[{$fix}:{$env}:{$time}]:{$msg}",
]
];
$data_string = json_encode($data);
$resp = \Frame\Core\Tools::curl($url, 'POST', $data_string, ['Content-Type: application/json;charset=utf-8']);
$resp = json_decode($resp, true);
if ($resp['errorcode']) {
return false;
}
return true;
}
9,如圖是我的報警信息示例