Laravel接入Prometheus的代码示例

Laravel接入Prometheus的代码示例,第1张

Laravel接入Prometheus的代码示例 本篇文章给大家带来的内容是关于Laravel接入Prometheus的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

在原有的基础上增加Counter计数器:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use traumferienwohnungen\PrometheusExporter\Middleware\AbstractResponseTimeMiddleware;

class PrometheusMonitor extends AbstractResponseTimeMiddleware
{
    protected function getRouteNames()
    {
        $routeNames = [];
        foreach (\Route::getRoutes() as $route){
            $routeNames[] = '/'.ltrim($route->uri(), '/');
        }
        return $routeNames;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (defined('LARAVEL_START')){
            $start = LARAVEL_START;
        } elseif (defined('LUMEN_START')){
            $start = LUMEN_START;
        } else {
            $start = microtime(true);
        }
        $this->request = $request;

        /** @var \Illuminate\Http\Response $response */
        $response = $next($request);

        $route_name = $this->getRouteName();
        $method = $request->getMethod();
        $status = $response->getStatusCode();

        $duration = microtime(true) - $start;
        $duration_milliseconds = $duration * 1000.0;
        $this->countRequest($route_name, $method, $status, $duration_milliseconds);

        $this->initRequestMetrics($method, $status);

        return $response;
    }

    public function getRouteName(){
        return request()->getRequestUri();
    }


    public function initRequestMetrics($method, $status)
    {
        $namespace = config('prometheus_exporter.namespace_http_server');

        $labelNames = $this->getRequestCounterLabelNames();

        $name = 'request_wuc';
        $help = 'http_requests count';
        $counter = $this->registry->getOrRegisterCounter(
            $namespace, $name, $help, $labelNames
        );

        $counter->incBy(1, [$this->getRouteName(), $method, $status]);
    }
}

以上就是Laravel接入Prometheus的代码示例的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/701203.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-23
下一篇 2022-04-23

发表评论

登录后才能评论

评论列表(0条)

保存