laravel 后台或者api框架异常钉钉告警提醒
  gOfhOzgl2UPX 2023年11月02日 39 0

中间件

Monitor
<?php

namespace App\Http\Middleware;

use Error;
use Closure;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Psy\Exception\ErrorException;
use Psy\Exception\FatalErrorException;

class Monitor
{
    /**
     * The App container
     *
     * @var Container
     */
    protected $container;

    /**
     * The Monitor Client
     *
     * @var
     */
    protected $monitor;

    /**
     * Create a new middleware instance.
     *
     * @param Container $container
     */
    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
//        dump("monitorDing");
        $enabled = config('monitorDing.enabled');
        try {
            $response = $next($request);
        } catch (Exception $e) {
            $response = $this->handleException($request, $e);
            $enabled && $this->sendText(sprintf("文件:%s (%s 行) 内容:%s", $e->getFile(), $e->getLine(), $e->getMessage()));

        } catch (Error $error) {
            $e = new FatalErrorException($error);
            $response = $this->handleException($request, $e);
            $enabled && $this->sendText(sprintf("文件:%s (%s 行) 内容:%s", $e->getFile(), $e->getLine(), $e->getMessage()));
        } catch (ErrorException $error) {
            $e = new FatalErrorException($error);
            $response = $this->handleException($request, $e);
            $enabled && $this->sendText(sprintf("文件:%s (%s 行) 内容:%s", $e->getFile(), $e->getLine(), $e->getMessage()));
        } finally {
            if ($response->getStatusCode() == '500' && (isset($response->exception) && $response->exception && $response->exception !== null)) {
                $sysName = config('monitorDing.web_name');

                if (strpos($_SERVER['HTTP_HOST'], 'liexin') !== false) {
                    $sysName = '本地' . $sysName;
                } else {
                    $sysName = '外网' . $sysName;
                }

                $this->sendText(substr($sysName . ":" . $response->exception, 0,
                        500) . ',请求数据:' . json_encode($request->input()) . "---[更多详情请看日志]");
            }
        }
        return $response;
    }

    /**
     * Handle the given exception.
     *
     * (Copy from Illuminate\Routing\Pipeline by Taylor Otwell)
     *
     * @param $passable
     * @param Exception $e
     * @return mixed
     * @throws Exception
     */
    protected function handleException($passable, Exception $e)
    {
        if (!$this->container->bound(ExceptionHandler::class) || !$passable instanceof Request) {
            throw $e;
        }

        $handler = $this->container->make(ExceptionHandler::class);

        $handler->report($e);

        return $handler->render($passable, $e);
    }


    /**
     * 发送文本类型的消息
     *
     * @param $content string 消息内容
     * @param array $atMobiles 被@人的手机号
     * @param bool $isAtAll 是否 @ 所有人
     * @throws SendErrorException
     */
    public function sendText($content, $atMobiles = [], $isAtAll = false)
    {
        $params = [
            'msgtype' => 'text',
            'text' => [
                'content' => $content,
            ],
            'at' => [
                'atMobiles' => $atMobiles,
                'isAtAll' => $isAtAll
            ]
        ];
        $this->send($params);
    }

    /**
     * 发送
     * @param array $params 请求需要的参数
     * @throws SendErrorException
     */
    private function send($params = [])
    {
        if (!config('monitorDing.enabled')) {
            \Log::info('~~ Monitor Ding ~~');
            \Log::info($params);
        } else {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, config("monitorDing.webhook"));
            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, json_encode($params));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            if (config()) {
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            }
            $data = json_decode(curl_exec($ch), true);
            curl_close($ch);

            if ($data['errcode']) {
//                throw new SendErrorException($data['errmsg']);
            }
        }

    }
}
App\Http\Kernel.php


protected $middleware = [
//............ 新增
    \App\Http\Middleware\Monitor::class
//...........
];

protected $routeMiddleware = [
    'monitor' => \App\Http\Middleware\Monitor::class,
];

配置文件

<?php
return [
    // 是否开启报错写入
    'enabled' => boolval(get_resource_config_section('app', 'pur')["monitorDing_enabled"]),

    // curl证书验证, 线下环境不用开启
    'curl_verify' => boolval(get_resource_config_section('app', 'pur')["monitorDing_curl_verify"]),

    'web_name'=>get_resource_config_section('app', 'pur')["monitorDing_web_name"],

    // webhook的值
    'webhook' => get_resource_config_section('app', 'pur')["monitorDing_webhook"],
];

 

最后新增钉钉机器人

laravel 后台或者api框架异常钉钉告警提醒_php

 

laravel 后台或者api框架异常钉钉告警提醒_json_02

 

laravel 后台或者api框架异常钉钉告警提醒_App_03

 

laravel 后台或者api框架异常钉钉告警提醒_json_04

 最后复制webhook即可

laravel 后台或者api框架异常钉钉告警提醒_json_05

 

laravel 后台或者api框架异常钉钉告警提醒_json_06

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  NT5NRjELxLp1   7天前   17   0   0 PHP
  yThMa20bw7iV   2024年02月19日   49   0   0 PHP
  NT5NRjELxLp1   2024年03月14日   49   0   0 PHP
gOfhOzgl2UPX
最新推荐 更多

2024-05-05