75 lines
1.9 KiB
PHP
75 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace LogDb\Monolog;
|
|
|
|
use Monolog\Handler\AbstractProcessingHandler;
|
|
use Monolog\Handler\HandlerInterface;
|
|
use Monolog\LogRecord;
|
|
use Symfony\Component\HttpClient\HttpClient;
|
|
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
|
|
|
class LogDbHandler extends AbstractProcessingHandler
|
|
{
|
|
private HttpClientInterface $client;
|
|
|
|
private bool $batching = false;
|
|
|
|
private array $batched = [];
|
|
|
|
public function __construct(
|
|
private readonly string $serverUrl,
|
|
private readonly ?string $scope = null,
|
|
private readonly ?string $source = null,
|
|
)
|
|
{
|
|
$this->client = HttpClient::createForBaseUri($this->serverUrl);
|
|
}
|
|
|
|
public function handleBatch(array $records): void
|
|
{
|
|
$this->batching = true;
|
|
parent::handleBatch($records);
|
|
$this->batching = false;
|
|
$this->commit();
|
|
}
|
|
|
|
protected function write(LogRecord $record): void
|
|
{
|
|
$event = [
|
|
'source' => $this->source,
|
|
'scope' => $this->scope,
|
|
'date' => $record->datetime->format('Y-m-d H:i:s P'),
|
|
'level' => $record->level->toPsrLogLevel(),
|
|
'brief' => $record->message,
|
|
'detail' => $record->formatted,
|
|
'context' => $record->context,
|
|
];
|
|
|
|
if ($this->batching) {
|
|
$this->batched[] = $event;
|
|
return;
|
|
}
|
|
|
|
try {
|
|
$response = $this->client->request('POST', '/api/logdb/v1/create-event', [
|
|
'json' => $event
|
|
]);
|
|
$response->getContent(true);
|
|
} catch (\Exception $e) {
|
|
// Silent fault.
|
|
}
|
|
}
|
|
|
|
private function commit(): void
|
|
{
|
|
try {
|
|
$response = $this->client->request('POST', '/api/logdb/v1/create-event', [
|
|
'json' => $this->batched
|
|
]);
|
|
$response->getContent(true);
|
|
} finally {
|
|
$this->batched = [];
|
|
}
|
|
|
|
}
|
|
} |