add influxdb and stat of page view

This commit is contained in:
Simon Vieille 2023-09-22 22:06:44 +02:00
parent d39759f88e
commit f4169d20e9
Signed by: deblan
GPG key ID: 579388D585F70417
2 changed files with 87 additions and 0 deletions

46
src/Api/InfluxDB.php Normal file
View file

@ -0,0 +1,46 @@
<?php
namespace App\Api;
use InfluxDB2\Client;
use InfluxDB2\Model\WritePrecision;
/**
* class InfluxDB.
*
* @author Simon Vieille <simon@deblan.fr>
*/
class InfluxDB
{
protected ?Client $client = null;
public function __construct(
protected ?string $url,
protected ?string $token,
protected ?string $bucket,
protected ?string $org,
protected bool $debug = false
) {
if (isset($this->url, $this->token, $this->bucket, $this->org)) {
$this->client = new Client([
'url' => $this->url,
'token' => $this->token,
'bucket' => $this->bucket,
'org' => $this->org,
'debug' => $this->debug,
'precision' => WritePrecision::S,
'timeout' => 1,
]);
}
}
public function isAvailable(): bool
{
return $this->getClient() !== null;
}
public function getClient(): ?Client
{
return $this->client;
}
}

View file

@ -0,0 +1,41 @@
<?php
namespace App\EventListener;
use App\Api\InfluxDB;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use InfluxDB2\WriteType;
use InfluxDB2\Point;
/**
* class StatListener.
*
* @author Simon Vieille <simon@deblan.fr>
*/
class StatListener
{
public function __construct(protected InfluxDB $influxDB)
{
}
public function onKernelRequest(RequestEvent $event)
{
if (!$this->influxDB->isAvailable()) {
return;
}
$client = $this->influxDB->getClient();
$writeApi = $client->createWriteApi(['writeType' => WriteType::SYNCHRONOUS]);
$pageView = new Point('page_view');
$pageView
->addTag('request', 'view')
->addField('value', 1)
->time(time())
;
$writeApi->write($pageView);
$writeApi->close();
$client->close();
}
}