phpkernel / logging
Lightweight file-based logger with automatic date-based rotation and context serialization
v1.0.0
2026-12-03 16:37 UTC
Requires
- php: >=8.5
- ext-posix: *
- phpkernel/system: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.95
- infection/infection: ^0.35.12
- phpstan/phpstan: ^2.3
- phpunit/phpunit: ^13.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Lightweight, concurrency-safe file logger for PHP 8.5+ with automatic year/month directory rotation and structured context serialization.
Features
- Automatic Log Rotation: Organizes logs by year (
YYYY/) and separateserror.MM.log,info.MM.log, andsystem.log. - PHP-FPM Safe: Uses exclusive file locking (
LOCK_EX) and explicit buffer flushing (fflush) to prevent interleaved log lines under concurrent requests. - Rich Context Normalization: Safely serializes
Throwable(including stack trace),BackedEnum,UnitEnum,JsonSerializable,Stringable,DateTimeInterface, objects, and resources into single-line JSON. - Resilient Formatting: Sanitizes line breaks in messages, enforces a maximum recursion depth (
10levels), and gracefully handles invalid UTF-8 or non-encodable values (NAN,INF). - Deterministic Time: Relies on
PHPKernel\System\ClockInterfacefor clean testability and predictable timestamps.
Requirements
- PHP
>= 8.5 ext-posixphpkernel/system: ^1.0
Installation
composer require phpkernel/logging
Usage
<?php
declare(strict_types=1);
use PHPKernel\Logging\FileLogger;
use PHPKernel\System\ClockInterface;
/** @var ClockInterface $clock */
$logger = new FileLogger($clock, '/var/log/app');
// Writes to /var/log/app/2026/info.12.log
$logger->info('User signed in', ['user_id' => 42, 'ip' => '127.0.0.1']);
// Writes to /var/log/app/2026/error.12.log
try {
throw new \RuntimeException('Database connection timeout', 504);
} catch (\Throwable $e) {
$logger->error('Query failed', ['exception' => $e]);
}
// Writes to /var/log/app/2026/system.log
$logger->system('Worker pool restarted');
Directory Layout & Format
Logs are stored inside year-based subdirectories relative to the configured base path:
/var/log/app/
└── 2026/
├── error.12.log
├── info.12.log
└── system.log
Each entry is written as a single line:
[2026-12-03 15:17:00] User signed in {"user_id":42,"ip":"127.0.0.1"}
Quality Assurance
The package is verified with strict static analysis, unit tests, and 100% mutation score:
# Run code style check, PHPStan (level max), and PHPUnit
composer check
# Run Infection mutation testing (100% MSI required)
composer mutate
# Run the full CI pipeline
composer ci
License
This library is open-sourced software licensed under the MIT license.