refactor: documents
All checks were successful
JS Unit Tests / test (pull_request) Successful in 21s
Build Test / build (pull_request) Successful in 25s
PHP Unit Tests / test (pull_request) Successful in 46s

Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
This commit is contained in:
2026-03-03 22:13:36 -05:00
parent 85e89dca87
commit 1f3e87535b
45 changed files with 1667 additions and 676 deletions

View File

@@ -40,11 +40,18 @@ class FileLogger implements LoggerInterface
public function log($level, $message, array $context = []): void
{
$timestamp = $this->formatTimestamp();
$interpolated = $this->interpolate((string)$message, $context);
// Extract tenant id injected by TenantAwareLogger; default to 'system'.
$tenantId = isset($context['__tenant']) && is_string($context['__tenant'])
? $context['__tenant']
: 'system';
unset($context['__tenant']);
$timestamp = $this->formatTimestamp();
$interpolated = $this->interpolate((string) $message, $context);
$payload = [
'time' => $timestamp,
'level' => strtolower((string)$level),
'time' => $timestamp,
'level' => strtolower((string) $level),
'tenant' => $tenantId,
'channel' => $this->channel,
'message' => $interpolated,
'context' => $this->sanitizeContext($context),
@@ -53,11 +60,12 @@ class FileLogger implements LoggerInterface
if ($json === false) {
// Fallback stringify if encoding fails (should be rare)
$json = json_encode([
'time' => $timestamp,
'level' => strtolower((string)$level),
'channel' => $this->channel,
'message' => $interpolated,
'context_error' => 'failed to encode context: '.json_last_error_msg(),
'time' => $timestamp,
'level' => strtolower((string) $level),
'tenant' => $tenantId,
'channel' => $this->channel,
'message' => $interpolated,
'context_error' => 'failed to encode context: ' . json_last_error_msg(),
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?: '{"error":"logging failure"}';
}
$this->write($json);

View File

@@ -0,0 +1,47 @@
<?php
namespace KTXC\Logger;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
/**
* PSR-3 decorator that discards messages below a configured minimum severity.
*
* Severity ordering (lower = more severe):
* emergency(0) > alert(1) > critical(2) > error(3) > warning(4) > notice(5) > info(6) > debug(7)
*
* Example: minLevel = 'warning' passes emergency, alert, critical, error, warning
* and silently discards notice, info, debug.
*/
class LevelFilterLogger implements LoggerInterface
{
private int $minSeverity;
public function __construct(
private readonly LoggerInterface $inner,
string $minLevel = LogLevel::DEBUG,
) {
LogLevelSeverity::validate($minLevel);
$this->minSeverity = LogLevelSeverity::severity($minLevel);
}
public function emergency($message, array $context = []): void { $this->log(LogLevel::EMERGENCY, $message, $context); }
public function alert($message, array $context = []): void { $this->log(LogLevel::ALERT, $message, $context); }
public function critical($message, array $context = []): void { $this->log(LogLevel::CRITICAL, $message, $context); }
public function error($message, array $context = []): void { $this->log(LogLevel::ERROR, $message, $context); }
public function warning($message, array $context = []): void { $this->log(LogLevel::WARNING, $message, $context); }
public function notice($message, array $context = []): void { $this->log(LogLevel::NOTICE, $message, $context); }
public function info($message, array $context = []): void { $this->log(LogLevel::INFO, $message, $context); }
public function debug($message, array $context = []): void { $this->log(LogLevel::DEBUG, $message, $context); }
public function log($level, $message, array $context = []): void
{
// Messages with severity numerically greater than minSeverity are less severe — discard them.
if (LogLevelSeverity::severity((string) $level) > $this->minSeverity) {
return;
}
$this->inner->log($level, $message, $context);
}
}

View File

@@ -0,0 +1,68 @@
<?php
namespace KTXC\Logger;
use Psr\Log\LogLevel;
/**
* Maps PSR-3 log level strings to integer severity values.
*
* Lower integer = higher severity (matches RFC 5424 / syslog convention):
* emergency = 0, alert = 1, critical = 2, error = 3,
* warning = 4, notice = 5, info = 6, debug = 7
*/
class LogLevelSeverity
{
private const MAP = [
LogLevel::EMERGENCY => 0,
LogLevel::ALERT => 1,
LogLevel::CRITICAL => 2,
LogLevel::ERROR => 3,
LogLevel::WARNING => 4,
LogLevel::NOTICE => 5,
LogLevel::INFO => 6,
LogLevel::DEBUG => 7,
];
/**
* Returns the integer severity for a PSR-3 level string.
*
* @throws \InvalidArgumentException for unknown level strings
*/
public static function severity(string $level): int
{
$normalized = strtolower($level);
if (!array_key_exists($normalized, self::MAP)) {
throw new \InvalidArgumentException(
sprintf(
'Unknown log level "%s". Valid levels are: %s.',
$level,
implode(', ', array_keys(self::MAP))
)
);
}
return self::MAP[$normalized];
}
/**
* Validates that a level string is a known PSR-3 level.
*
* @throws \InvalidArgumentException for unknown level strings
*/
public static function validate(string $level): void
{
self::severity($level); // throws on unknown
}
/**
* Returns all valid PSR-3 level strings ordered from most to least severe.
*
* @return string[]
*/
public static function levels(): array
{
return array_keys(self::MAP);
}
}

View File

@@ -0,0 +1,87 @@
<?php
namespace KTXC\Logger;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* Creates a PSR-3 LoggerInterface instance from the application config.
*
* Reads the 'log' key from the system config array and builds:
* 1. A driver-specific inner logger (file, systemd, syslog, null).
* 2. A LevelFilterLogger decorator that discards messages below the
* configured minimum level.
*
* Per-tenant routing (TenantAwareLogger) is applied separately inside the
* DI container definition in Kernel::configureContainer(), because that
* requires access to the SessionTenant singleton which lives in the container.
*
* Supported config keys inside $config['log']:
*
* driver string 'file' | 'systemd' | 'syslog' | 'null' default: 'file'
* level string PSR-3 level string (minimum to log) default: 'debug'
* per_tenant bool Route to per-tenant files (DI-level only) default: false
*
* -- file driver --
* path ?string Absolute log directory, null = {root}/var/log
* channel string File basename without extension default: 'app'
*
* -- systemd driver --
* channel string Channel tag embedded in each line default: 'app'
*
* -- syslog driver --
* ident string openlog() identity tag default: 'ktrix'
* facility int openlog() facility constant default: LOG_USER
* channel string Prefix embedded in each syslog message default: 'app'
*/
class LoggerFactory
{
/**
* Build and return a configured, level-filtered PSR-3 logger.
*
* @param array $config The full system config array (reads $config['log']).
* @param string $projectDir Absolute project root path (used for default file path).
*/
public static function create(array $config, string $projectDir): LoggerInterface
{
$logConfig = $config['log'] ?? [];
$driver = $logConfig['driver'] ?? 'file';
$level = $logConfig['level'] ?? 'debug';
$channel = $logConfig['channel'] ?? 'app';
// Validate level early for a clear error message.
LogLevelSeverity::validate($level);
$inner = match ($driver) {
'file' => self::buildFileLogger($logConfig, $projectDir, $channel),
'systemd' => new SystemdLogger($channel),
'syslog' => new SyslogLogger(
$logConfig['ident'] ?? 'ktrix',
$logConfig['facility'] ?? LOG_USER,
$channel,
),
'null' => new NullLogger(),
default => throw new \RuntimeException(
sprintf(
'Unknown log driver "%s". Supported drivers: file, systemd, syslog, null.',
$driver
)
),
};
return new LevelFilterLogger($inner, $level);
}
private static function buildFileLogger(array $logConfig, string $projectDir, string $channel): FileLogger
{
$path = $logConfig['path'] ?? null;
if ($path === null || $path === '') {
$path = $projectDir . '/var/log';
}
return new FileLogger($path, $channel);
}
}

View File

@@ -0,0 +1,94 @@
<?php
namespace KTXC\Logger;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
/**
* PSR-3 logger that writes via PHP's built-in syslog() facility.
*
* Each message is prefixed with "[channel] " so entries can be filtered easily
* in /var/log/syslog (or equivalent) or via journalctl -t {ident}.
*/
class SyslogLogger implements LoggerInterface
{
/** Maps PSR-3 levels to PHP syslog priority constants */
private const PRIORITY = [
LogLevel::EMERGENCY => LOG_EMERG,
LogLevel::ALERT => LOG_ALERT,
LogLevel::CRITICAL => LOG_CRIT,
LogLevel::ERROR => LOG_ERR,
LogLevel::WARNING => LOG_WARNING,
LogLevel::NOTICE => LOG_NOTICE,
LogLevel::INFO => LOG_INFO,
LogLevel::DEBUG => LOG_DEBUG,
];
public function __construct(
private readonly string $ident = 'ktrix',
private readonly int $facility = LOG_USER,
private readonly string $channel = 'app',
) {}
public function emergency($message, array $context = []): void { $this->log(LogLevel::EMERGENCY, $message, $context); }
public function alert($message, array $context = []): void { $this->log(LogLevel::ALERT, $message, $context); }
public function critical($message, array $context = []): void { $this->log(LogLevel::CRITICAL, $message, $context); }
public function error($message, array $context = []): void { $this->log(LogLevel::ERROR, $message, $context); }
public function warning($message, array $context = []): void { $this->log(LogLevel::WARNING, $message, $context); }
public function notice($message, array $context = []): void { $this->log(LogLevel::NOTICE, $message, $context); }
public function info($message, array $context = []): void { $this->log(LogLevel::INFO, $message, $context); }
public function debug($message, array $context = []): void { $this->log(LogLevel::DEBUG, $message, $context); }
public function log($level, $message, array $context = []): void
{
// Extract tenant id injected by TenantAwareLogger; default to 'system'.
$tenantId = isset($context['__tenant']) && is_string($context['__tenant'])
? $context['__tenant']
: 'system';
unset($context['__tenant']);
$level = strtolower((string) $level);
$priority = self::PRIORITY[$level] ?? LOG_DEBUG;
$interpolated = $this->interpolate((string) $message, $context);
$contextStr = empty($context) ? '' : ' ' . $this->encodeContext($context);
$entry = sprintf('[%s] [%s] %s%s', $this->channel, $tenantId, $interpolated, $contextStr);
openlog($this->ident, LOG_NDELAY | LOG_PID, $this->facility);
syslog($priority, $entry);
closelog();
}
private function interpolate(string $message, array $context): string
{
if (!str_contains($message, '{')) {
return $message;
}
$replace = [];
foreach ($context as $key => $val) {
if (!is_array($val) && !is_object($val)) {
$replace['{' . $key . '}'] = (string) $val;
}
}
return strtr($message, $replace);
}
private function encodeContext(array $context): string
{
$clean = [];
foreach ($context as $k => $v) {
if ($v instanceof \Throwable) {
$clean[$k] = ['type' => get_class($v), 'message' => $v->getMessage()];
} elseif (is_resource($v)) {
$clean[$k] = 'resource(' . get_resource_type($v) . ')';
} elseif (is_object($v)) {
$clean[$k] = method_exists($v, '__toString') ? (string) $v : ['object' => get_class($v)];
} else {
$clean[$k] = $v;
}
}
return json_encode($clean, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?: '{}';
}
}

View File

@@ -0,0 +1,112 @@
<?php
namespace KTXC\Logger;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
/**
* PSR-3 logger that writes to stderr using the journald/systemd SD_JOURNAL_PREFIX
* format: a syslog-priority number wrapped in angle brackets followed by the message.
*
* journald automatically parses the "<N>" prefix and maps it to the corresponding
* log priority, so log entries appear in the journal with the correct severity.
*
* Format: <priority>LEVEL [channel] interpolated-message {"context":"key",...}
*/
class SystemdLogger implements LoggerInterface
{
/** Maps PSR-3 levels to RFC 5424 / syslog priority numbers */
private const PRIORITY = [
LogLevel::EMERGENCY => 0,
LogLevel::ALERT => 1,
LogLevel::CRITICAL => 2,
LogLevel::ERROR => 3,
LogLevel::WARNING => 4,
LogLevel::NOTICE => 5,
LogLevel::INFO => 6,
LogLevel::DEBUG => 7,
];
/** @var resource */
private $stderr;
public function __construct(private readonly string $channel = 'app')
{
$this->stderr = fopen('php://stderr', 'w');
}
public function __destruct()
{
if (is_resource($this->stderr)) {
fclose($this->stderr);
}
}
public function emergency($message, array $context = []): void { $this->log(LogLevel::EMERGENCY, $message, $context); }
public function alert($message, array $context = []): void { $this->log(LogLevel::ALERT, $message, $context); }
public function critical($message, array $context = []): void { $this->log(LogLevel::CRITICAL, $message, $context); }
public function error($message, array $context = []): void { $this->log(LogLevel::ERROR, $message, $context); }
public function warning($message, array $context = []): void { $this->log(LogLevel::WARNING, $message, $context); }
public function notice($message, array $context = []): void { $this->log(LogLevel::NOTICE, $message, $context); }
public function info($message, array $context = []): void { $this->log(LogLevel::INFO, $message, $context); }
public function debug($message, array $context = []): void { $this->log(LogLevel::DEBUG, $message, $context); }
public function log($level, $message, array $context = []): void
{
// Extract tenant id injected by TenantAwareLogger; default to 'system'.
$tenantId = isset($context['__tenant']) && is_string($context['__tenant'])
? $context['__tenant']
: 'system';
unset($context['__tenant']);
$level = strtolower((string) $level);
$priority = self::PRIORITY[$level] ?? 7;
$interpolated = $this->interpolate((string) $message, $context);
$contextStr = empty($context) ? '' : ' ' . $this->encodeContext($context);
$line = sprintf(
"<%d>%s [%s] [%s] %s%s\n",
$priority,
strtoupper($level),
$this->channel,
$tenantId,
$interpolated,
$contextStr,
);
fwrite($this->stderr, $line);
}
private function interpolate(string $message, array $context): string
{
if (!str_contains($message, '{')) {
return $message;
}
$replace = [];
foreach ($context as $key => $val) {
if (!is_array($val) && !is_object($val)) {
$replace['{' . $key . '}'] = (string) $val;
}
}
return strtr($message, $replace);
}
private function encodeContext(array $context): string
{
$clean = [];
foreach ($context as $k => $v) {
if ($v instanceof \Throwable) {
$clean[$k] = ['type' => get_class($v), 'message' => $v->getMessage()];
} elseif (is_resource($v)) {
$clean[$k] = 'resource(' . get_resource_type($v) . ')';
} elseif (is_object($v)) {
$clean[$k] = method_exists($v, '__toString') ? (string) $v : ['object' => get_class($v)];
} else {
$clean[$k] = $v;
}
}
return json_encode($clean, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?: '{}';
}
}

View File

@@ -0,0 +1,93 @@
<?php
namespace KTXC\Logger;
use KTXC\SessionTenant;
use Psr\Log\LoggerInterface;
/**
* PSR-3 decorator with two responsibilities:
*
* 1. Tenant-id injection — every log record is enriched with a `tenant` field.
* When a tenant session is active the real tenant identifier is used; otherwise
* the value is "system" (boot phase, CLI, bad-domain rejections, etc.).
* The id is passed to inner loggers via the reserved `__tenant` context key,
* which each concrete logger (FileLogger, SystemdLogger, SyslogLogger) extracts
* and renders as a top-level field, then removes from context before output.
*
* 2. Per-tenant file routing (optional, controlled by $perTenant) — when enabled,
* writes for an active tenant are routed to:
* {logDir}/tenant/{tenantIdentifier}/{channel}.jsonl
* Messages that carry tenant "system" always go to the global logger.
*
* Both behaviours rely on a live SessionTenant reference that is populated lazily
* by TenantMiddleware — the same pattern the cache stores use in Kernel::configureContainer().
*/
class TenantAwareLogger implements LoggerInterface
{
/** @var array<string, LoggerInterface> Per-tenant logger cache, keyed by tenant identifier. */
private array $tenantLoggers = [];
/**
* @param LoggerInterface $globalLogger Fallback logger (also used when perTenant = false).
* @param SessionTenant $sessionTenant Live reference configured by TenantMiddleware.
* @param string $logDir Base log directory (e.g. /var/www/app/var/log).
* @param string $channel Log file basename (e.g. 'app' → app.jsonl).
* @param string $minLevel Minimum PSR-3 level for lazily-created per-tenant loggers.
* @param bool $perTenant When true, route tenant writes to per-tenant files.
*/
public function __construct(
private readonly LoggerInterface $globalLogger,
private readonly SessionTenant $sessionTenant,
private readonly string $logDir,
private readonly string $channel = 'app',
private readonly string $minLevel = 'debug',
private readonly bool $perTenant = false,
) {
LogLevelSeverity::validate($minLevel);
}
public function emergency($message, array $context = []): void { $this->log('emergency', $message, $context); }
public function alert($message, array $context = []): void { $this->log('alert', $message, $context); }
public function critical($message, array $context = []): void { $this->log('critical', $message, $context); }
public function error($message, array $context = []): void { $this->log('error', $message, $context); }
public function warning($message, array $context = []): void { $this->log('warning', $message, $context); }
public function notice($message, array $context = []): void { $this->log('notice', $message, $context); }
public function info($message, array $context = []): void { $this->log('info', $message, $context); }
public function debug($message, array $context = []): void { $this->log('debug', $message, $context); }
public function log($level, $message, array $context = []): void
{
// Resolve current tenant id; fall back to 'system' for CLI / boot phase.
$tenantId = 'system';
if ($this->sessionTenant->configured()) {
$tenantId = $this->sessionTenant->identifier() ?? 'system';
}
// Inject tenant id as a reserved context key that concrete loggers extract.
$context['__tenant'] = $tenantId;
$this->resolveLogger($tenantId)->log($level, $message, $context);
}
/**
* Returns the logger to write to for the given tenant.
* When per-tenant routing is disabled (or tenant is "system"), always returns the global logger.
*/
private function resolveLogger(string $tenantId): LoggerInterface
{
if (!$this->perTenant || $tenantId === 'system') {
return $this->globalLogger;
}
if (!isset($this->tenantLoggers[$tenantId])) {
$tenantLogDir = rtrim($this->logDir, '/') . '/tenant/' . $tenantId;
$this->tenantLoggers[$tenantId] = new LevelFilterLogger(
new FileLogger($tenantLogDir, $this->channel),
$this->minLevel,
);
}
return $this->tenantLoggers[$tenantId];
}
}