PHP_AdminTool_Projekt/app/Controllers/LogViewerController.php
2025-12-17 12:07:50 +01:00

124 lines
3.3 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Services\Logging\LoggingService;
use App\Services\Logging\LogViewerService;
/**
* Controller für den Log Viewer (read-only).
*/
class LogViewerController
{
/** @var array<string, mixed> */
private array $config;
private LoggingService $logger;
private LogViewerService $logViewer;
/**
* @param array<string, mixed> $config
*/
public function __construct(array $config)
{
$this->config = $config;
$loggingConfig = $config['logging'] ?? [];
$this->logger = new LoggingService($loggingConfig);
$this->logViewer = new LogViewerService($loggingConfig);
}
/**
* Zeigt den Log Viewer an.
*
* Erwartet optionale GET-Parameter:
* - file (Dateiname, z.B. app.log)
* - level (DEBUG|INFO|WARNING|ERROR)
* - q (Suche)
* - lines (Anzahl Zeilen, Default 200)
*
* @return array<string, mixed>
*/
public function show(): array
{
$files = $this->logViewer->listLogFiles();
$selectedFile = (string)($_GET['file'] ?? '');
if ($selectedFile === '' && isset($files[0]['name'])) {
$selectedFile = (string)$files[0]['name'];
}
$level = (string)($_GET['level'] ?? '');
$level = strtoupper(trim($level));
if ($level === '') {
$level = '';
}
$q = (string)($_GET['q'] ?? '');
$q = trim($q);
$lines = (int)($_GET['lines'] ?? 200);
if ($lines <= 0) {
$lines = 200;
}
if ($lines > 2000) {
$lines = 2000;
}
$error = null;
$fileMeta = null;
$entries = [];
try {
if ($selectedFile !== '') {
$fileMeta = $this->logViewer->getFileMeta($selectedFile);
$entries = $this->logViewer->getEntries(
$selectedFile,
$lines,
$level !== '' ? $level : null,
$q !== '' ? $q : null
);
if ($fileMeta === null) {
$error = 'Die ausgewählte Log-Datei ist nicht verfügbar.';
$entries = [];
}
} else {
$error = 'Es wurde keine Log-Datei gefunden.';
}
} catch (\Throwable $ex) {
$this->logger->logException(
'LogViewerController: Fehler beim Laden der Logs.',
$ex,
[
'route' => 'logs',
'file' => $selectedFile,
]
);
$error = 'Technischer Fehler beim Laden der Logs. Details stehen im app.log.';
}
$viewPath = __DIR__ . '/../../public/views/logs.php';
return [
'view' => $viewPath,
'data' => [
'loginPage' => false,
'files' => $files,
'selectedFile' => $selectedFile,
'fileMeta' => $fileMeta,
'entries' => $entries,
'filterLevel' => $level,
'searchQuery' => $q,
'lines' => $lines,
'error' => $error,
],
'pageTitle' => 'Logs',
'activeMenu' => 'logs',
];
}
}