Add date, event batching

This commit is contained in:
2025-09-06 01:35:04 +02:00
parent 5010d085f5
commit f710aa0e6f
3 changed files with 42 additions and 7 deletions

1
.gitignore vendored
View File

@@ -1 +1,2 @@
/vendor/
/*.zip

View File

@@ -26,18 +26,36 @@ class LogDbClient
case 'http':
$url = $this->server . "/api/logdb/v1/create-event";
if (!str_starts_with($url, "http")) $url = "http://{$url}";
$this->sendHttp($event, $url);
$this->sendHttp(json_encode($event), $url);
break;
case 'udp':
[$ip,$port] = explode(":", $this->server, 2);
$this->sendUdp($event, $ip, $port);
$this->sendUdp(json_encode($event), $ip, $port);
break;
}
}
private function sendHttp(LogEvent $event, string $url): void
public function logEventBatch(array $events): 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(json_encode($event), $url);
break;
case 'udp':
foreach ($events as $event) {
if ($event instanceof LogEvent) {
[$ip,$port] = explode(":", $this->server, 2);
$this->sendUdp(json_encode($event), $ip, $port);
}
}
break;
}
}
private function sendHttp(string $message, string $url): void
{
$message = json_encode($event);
$context = stream_context_create([
'http' => [
'method' => 'POST',
@@ -50,10 +68,9 @@ class LogDbClient
$response = file_get_contents($url, context:$context);
}
private function sendUdp(LogEvent $event, string $ip, int $port): void
private function sendUdp(string $message, 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);
}

View File

@@ -2,7 +2,9 @@
namespace LogDb\Client;
class LogEvent
use JsonSerializable;
class LogEvent implements JsonSerializable
{
public function __construct(
public readonly string $brief,
@@ -12,8 +14,23 @@ class LogEvent
public readonly ?string $source = null,
public readonly ?string $origin = null,
public readonly array $context = [],
public readonly ?DateTime $date = null,
)
{
}
public function jsonSerialize(): mixed
{
return [
'brief' => $this->brief,
'detail' => $this->detail,
'level' => $this->level,
'scope' => $this->scope,
'source' => $this->source,
'origin' => $this->origin,
'context' => $this->context,
'date' => $this->date?->format('Y-m-d H:i:s P'),
];
}
}