JsonLineFormatter.php
1 week ago
LogDirectoryManager.php
1 week ago
LogRetentionCleanupService.php
1 week ago
LogSanitizer.php
1 week ago
MonologChannelLogger.php
1 week ago
MonologLoggerFactory.php
1 week ago
RequestIdProcessor.php
1 week ago
LogRetentionCleanupService.php
68 lines
| 1 | <?php |
| 2 | |
| 3 | namespace AmeliaBooking\Infrastructure\Services\Logger; |
| 4 | |
| 5 | use AmeliaBooking\Domain\Services\Settings\SettingsService; |
| 6 | |
| 7 | /** |
| 8 | * Class LogRetentionCleanupService |
| 9 | * |
| 10 | * WP-Cron callback: deletes log files older than the configured retention window. |
| 11 | * Age is determined from the UTC date embedded in the filename |
| 12 | * (amelia-{hash}-{channel}-YYYY-MM-DD.log). |
| 13 | * |
| 14 | * @package AmeliaBooking\Infrastructure\Services\Logger |
| 15 | */ |
| 16 | class LogRetentionCleanupService |
| 17 | { |
| 18 | private const DEFAULT_RETENTION_DAYS = 30; |
| 19 | |
| 20 | private SettingsService $settingsService; |
| 21 | |
| 22 | public function __construct(SettingsService $settingsService) |
| 23 | { |
| 24 | $this->settingsService = $settingsService; |
| 25 | } |
| 26 | |
| 27 | public function cleanup(): void |
| 28 | { |
| 29 | $retentionDays = (int) $this->settingsService->getSetting( |
| 30 | 'logging', |
| 31 | 'retentionDays', |
| 32 | self::DEFAULT_RETENTION_DAYS |
| 33 | ); |
| 34 | |
| 35 | if ($retentionDays <= 0) { |
| 36 | return; |
| 37 | } |
| 38 | |
| 39 | $directory = LogDirectoryManager::ensureDirectory(); |
| 40 | $prefix = LogDirectoryManager::getFilenamePrefix(); |
| 41 | $cutoff = strtotime(gmdate('Y-m-d', time() - ($retentionDays * DAY_IN_SECONDS)) . ' UTC'); |
| 42 | |
| 43 | if ($cutoff === false) { |
| 44 | return; |
| 45 | } |
| 46 | |
| 47 | // Monolog RotatingFileHandler: amelia-{hash}-{channel}-YYYY-MM-DD.log |
| 48 | // Also matches legacy size-split files: amelia-{hash}-{channel}-YYYY-MM-DD-N.log |
| 49 | $pattern = '/^' . preg_quote($prefix, '/') . '-[a-z0-9_-]+-(\d{4}-\d{2}-\d{2})(?:-\d+)?\.log$/i'; |
| 50 | |
| 51 | foreach (glob($directory . '/' . $prefix . '-*.log') ?: [] as $file) { |
| 52 | if (!is_file($file)) { |
| 53 | continue; |
| 54 | } |
| 55 | |
| 56 | if (!preg_match($pattern, basename($file), $matches)) { |
| 57 | continue; |
| 58 | } |
| 59 | |
| 60 | $fileDate = strtotime($matches[1] . ' UTC'); |
| 61 | |
| 62 | if ($fileDate !== false && $fileDate < $cutoff) { |
| 63 | @unlink($file); |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 |