Initial commit
This commit is contained in:
61
src/LogDbClient.php
Normal file
61
src/LogDbClient.php
Normal file
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace LogDb\Client;
|
||||
|
||||
class LogDbClient
|
||||
{
|
||||
|
||||
private mixed $socket = null;
|
||||
|
||||
public function __destruct()
|
||||
{
|
||||
if (\is_resource($this->socket)) socket_close($this->socket);
|
||||
|
||||
}
|
||||
|
||||
public function __construct(
|
||||
private readonly string $server,
|
||||
private readonly string $type = 'http'
|
||||
)
|
||||
{
|
||||
}
|
||||
|
||||
public function logEvent(LogEvent $event): void
|
||||
{
|
||||
switch ($this->type) {
|
||||
case 'http':
|
||||
$url = $this->server . "/api/logdb/v1/create-event";
|
||||
if (!str_starts_with($url, "http")) $url = "http://{$url}";
|
||||
$this->sendHttp($event, $url);
|
||||
break;
|
||||
case 'udp':
|
||||
[$ip,$port] = explode(":", $this->server, 2);
|
||||
$this->sendUdp($event, $ip, $port);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private function sendHttp(LogEvent $event, string $url): void
|
||||
{
|
||||
$message = json_encode($event);
|
||||
$context = stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'POST',
|
||||
'header' => [
|
||||
'content-type: application/json'
|
||||
],
|
||||
'content' => $message
|
||||
]
|
||||
]);
|
||||
$response = file_get_contents($url, context:$context);
|
||||
}
|
||||
|
||||
private function sendUdp(LogEvent $event, string $ip, int $port): void
|
||||
{
|
||||
$this->socket ??= socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
|
||||
$message = json_encode($event);
|
||||
$len = strlen($message);
|
||||
socket_sendto($this->socket, $message, $len, 0, $ip, $port);
|
||||
}
|
||||
}
|
||||
|
19
src/LogEvent.php
Normal file
19
src/LogEvent.php
Normal file
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace LogDb\Client;
|
||||
|
||||
class LogEvent
|
||||
{
|
||||
public function __construct(
|
||||
public readonly string $brief,
|
||||
public readonly ?string $detail = null,
|
||||
public readonly ?string $level = null,
|
||||
public readonly ?string $scope = null,
|
||||
public readonly ?string $source = null,
|
||||
public readonly ?string $origin = null,
|
||||
public readonly array $context = [],
|
||||
)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user