使用场景,服务器报异常错误,想要及时收到报警信息并处理
环境介绍,本博使用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,如图是我的报警信息示例