61 lines
1.5 KiB
PHP
61 lines
1.5 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
namespace UploadLogger\Core\Services;
|
|
|
|
final class LogService
|
|
{
|
|
private string $logFile;
|
|
/** @var array<string,mixed> */
|
|
private array $ctx;
|
|
|
|
/**
|
|
* @param string $logFile
|
|
* @param array<string,mixed> $ctx
|
|
*/
|
|
public function __construct(string $logFile, array $ctx = [])
|
|
{
|
|
$this->logFile = $logFile;
|
|
$this->ctx = $ctx;
|
|
}
|
|
|
|
/**
|
|
* @param string $event
|
|
* @param array<string,mixed> $data
|
|
*/
|
|
public function logEvent(string $event, array $data = []): void
|
|
{
|
|
$payload = array_merge(['ts' => gmdate('c'), 'event' => $event], $this->ctx, $data);
|
|
|
|
$payload = $this->normalize($payload);
|
|
|
|
$json = json_encode($payload, JSON_UNESCAPED_SLASHES);
|
|
if ($json === false) {
|
|
$json = json_encode([
|
|
'ts' => gmdate('c'),
|
|
'event' => 'log_error',
|
|
'error' => json_last_error_msg(),
|
|
], JSON_UNESCAPED_SLASHES);
|
|
}
|
|
|
|
@file_put_contents($this->logFile, $json . "\n", FILE_APPEND | LOCK_EX);
|
|
}
|
|
|
|
private function normalize(mixed $value): mixed
|
|
{
|
|
if (is_array($value)) {
|
|
$out = [];
|
|
foreach ($value as $k => $v) {
|
|
$out[$k] = $this->normalize($v);
|
|
}
|
|
return $out;
|
|
}
|
|
|
|
if (is_bool($value) || is_int($value) || is_float($value) || $value === null) {
|
|
return $value;
|
|
}
|
|
|
|
$str = (string)$value;
|
|
return preg_replace('/[\x00-\x1F\x7F]/', '_', $str);
|
|
}
|
|
}
|