php-spark/plugins/com.noccy.apiclient/Log/RequestLog.php

64 lines
1.8 KiB
PHP
Raw Permalink Normal View History

<?php
namespace SparkPlug\Com\Noccy\ApiClient\Log;
use JsonSerializable;
use Psr\Http\Message\ResponseInterface;
use SparkPlug\Com\Noccy\ApiClient\Log\RequestData as LogRequestData;
use SparkPlug\Com\Noccy\ApiClient\Request\Request;
class RequestLog
{
private ?string $lastLog = null;
private string $filename;
private array $append = [];
const MAX_EVENTS_PER_FILE = 100;
public function __construct(string $logfile)
{
$this->filename = $logfile;
}
public function append(RequestData $request)
{
$this->append[] = $request;
}
public function flush()
{
if (file_exists($this->filename)) {
$log = json_decode(file_get_contents($this->filename), true);
} else {
$log = [
'lastlog' => null,
'events' => []
];
}
while (count($this->append) > 0) {
$append = array_shift($this->append);
array_push($log['events'], $append);
$json = json_encode($log, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
if (count($log['events']) >= self::MAX_EVENTS_PER_FILE) {
do {
$newlog = sprintf("%s.%04x", $this->filename, rand(0,65535));
} while (file_exists($newlog));
file_put_contents($newlog, $json);
$log['lastlog'] = basename($newlog);
$log['events'] = [];
} else {
file_put_contents($this->filename."~", $json);
if (filesize($this->filename."~") > 0) {
rename($this->filename."~", $this->filename);
} else {
fprintf(STDERR, "error: Null size log writing requestlog %s\n", $this->filename);
}
}
}
}
}