# TerraFlowCMS Logging-System

Das TerraFlowCMS verfügt über ein umfassendes, strukturiertes Logging-System, das sowohl vom Core als auch von Plugins verwendet werden kann.

## Übersicht

Das Logging-System bietet:
- **Strukturiertes Logging** mit automatischem Kontext
- **Plugin-Unterstützung** für einfache Integration
- **Log-Rotation** und automatische Bereinigung
- **Performance-Monitoring** und Sicherheits-Logging
- **Admin-Commands** für Log-Verwaltung

## Monolog: Development vs. Production

Die zentrale Monolog-Konfiguration liegt in `config/packages/monolog.yaml`.

| Umgebung | Handler `main` | Level | Ausgabe |
|----------|----------------|-------|---------|
| **dev** | `stream` | `debug` | `%kernel.logs_dir%/dev.log` (typisch `var/log/dev.log`) |
| **prod** | `rotating_file` | `info` | `%kernel.logs_dir%/prod.log` mit Rotation (`max_files: 14`) |
| **prod** `console` | `console` | `warning` | Konsole (weniger Lärm in Orchestrierung) |
| **prod** `deprecation` | `stream` | `notice` | `%kernel.logs_dir%/deprecation.log` |

**Hinweise**

- In **Production** gibt es **kein** `fingers_crossed` auf dem Haupt-Handler: Meldungen ab **INFO** (inkl. NOTICE, WARNING, ERROR, CRITICAL) werden zuverlässig geschrieben; **DEBUG** bleibt aus.
- Der Kanal **`app`** ist in Symfony der **Standard-Logger** (`@logger`); strukturierte TerraFlow-Logs über `LoggingService` nutzen den eigenen Kanal **`terraflow`** (`@monolog.logger.terraflow`).
- **`RequestContextProcessor`** (`src/Monolog/RequestContextProcessor.php`) hängt am Handler **`main`** und ergänzt jede Zeile um **`extra`**: `request_uri`, `http_method`, `client_ip`, `request_id` (Header `X-Request-Id`, sonst pro Request generiert).
- **Nur dev:** `RequestDurationLogSubscriber` schreibt nach Abschluss des Haupt-Requests eine **INFO**-Zeile `HTTP request completed` mit `duration_ms`, `method`, `uri`.

### PSR-Level (Kurz)

| Level | Typische Verwendung |
|-------|----------------------|
| DEBUG | Entwicklung, detaillierte Abläufe |
| INFO | Normale Betriebsereignisse |
| NOTICE | Ungewöhnlich, aber kein Fehler |
| WARNING | Abweichung, sollte geprüft werden |
| ERROR | Fehler, Funktion beeinträchtigt |
| CRITICAL | schwerer Ausfall |

## Core-Services

### LoggingService

Der Hauptservice für alle Logging-Operationen:

```php
use TerraFlow\Service\LoggingService;

// Basis-Logging
$loggingService->debug('Debug-Nachricht', ['context' => 'data']);
$loggingService->info('Info-Nachricht', ['user_id' => 123]);
$loggingService->warning('Warnung', ['issue' => 'description']);
$loggingService->error('Fehler', ['error_code' => 'E001']);
$loggingService->critical('Kritischer Fehler', ['system' => 'down']);

// Spezialisierte Logging-Methoden
$loggingService->logUserAction('user_login', ['ip' => '192.168.1.1']);
$loggingService->logPluginAction('MyPlugin', 'plugin_activated', ['version' => '1.0.0']);
$loggingService->logSystemAction('cache_cleared', ['tags' => ['pages', 'media']]);
$loggingService->logDatabaseAction('create', 'User', 123, ['fields' => ['name', 'email']]);
$loggingService->logApiRequest('/api/users', 'GET', ['params' => ['page' => 1]]);
$loggingService->logApiResponse('/api/users', 200, 0.5, ['results' => 10]);
$loggingService->logSecurityEvent('failed_login', ['username' => 'admin', 'ip' => '192.168.1.1']);
$loggingService->logPerformance('database_query', 0.2, ['query' => 'SELECT * FROM users']);
$loggingService->logCacheOperation('set', 'user_123', ['ttl' => 3600]);
$loggingService->logFileOperation('upload', '/uploads/image.jpg', ['size' => 1024]);
```

### LogCleanupService

Service für Log-Verwaltung und -Bereinigung:

```php
use TerraFlow\Service\LogCleanupService;

// Vollständige Bereinigung
$results = $logCleanupService->cleanupLogs();

// Log-Rotation
$results = $logCleanupService->rotateLogs();

// Kompression alter Logs
$results = $logCleanupService->compressOldLogs();

// Statistiken abrufen
$stats = $logCleanupService->getLogStatistics();
```

## Plugin-Integration

### LoggingAwarePluginInterface

Plugins können das Logging-System über das Interface verwenden:

```php
use TerraFlow\Plugin\LoggingAwarePluginInterface;
use TerraFlow\Interface\LoggingInterface;

class MyPlugin extends AbstractPlugin implements LoggingAwarePluginInterface
{
    private ?LoggingInterface $loggingService = null;

    public function setLoggingService(LoggingInterface $loggingService): void
    {
        $this->loggingService = $loggingService;
    }

    public function getPluginName(): string
    {
        return 'MyPlugin';
    }

    public function activate(): bool
    {
        if ($this->loggingService) {
            $this->loggingService->logPluginAction('MyPlugin', 'plugin_activated', [
                'version' => $this->getPluginInfo()->getVersion()
            ]);
        }
        
        return parent::activate();
    }
}
```

### AbstractLoggingAwarePlugin

Einfachere Integration über die abstrakte Basis-Klasse:

```php
use TerraFlow\Plugin\AbstractLoggingAwarePlugin;

class MyPlugin extends AbstractLoggingAwarePlugin
{
    public function activate(): bool
    {
        // Automatisches Plugin-Logging
        $this->logPluginAction('plugin_activated', [
            'version' => $this->getPluginInfo()->getVersion()
        ]);

        // Standard-Logging
        $this->log('info', 'Plugin wurde aktiviert');
        $this->log('debug', 'Plugin-Konfiguration geladen', ['config' => $this->getConfig()]);

        return parent::activate();
    }

    public function handleUserAction($action, $data)
    {
        // Benutzer-Aktionen loggen
        $this->logUserAction($action, $data);

        // Performance messen
        $startTime = microtime(true);
        // ... Plugin-Logik ...
        $executionTime = microtime(true) - $startTime;
        $this->logPerformance('user_action_processing', $executionTime, ['action' => $action]);
    }
}
```

## Log-Konfiguration

### Services.yaml

```yaml
# Logging Service (Kanal terraflow — siehe monolog.yaml → channels)
TerraFlow\Service\LoggingService:
    arguments:
        $logger: '@monolog.logger.terraflow'
        $security: '@security.helper'
        $filesystem: '@filesystem'
        $projectDir: '%kernel.project_dir%'

# Request-Kontext nur für Handler „main“ (nicht autoconfigure, sonst an alle Logger)
TerraFlow\Monolog\RequestContextProcessor:
    autoconfigure: false
    autowire: true
    tags:
        - { name: monolog.processor, handler: main }

# Logging Interface Alias
TerraFlow\Interface\LoggingInterface: '@TerraFlow\Service\LoggingService'

# Log Cleanup Service
TerraFlow\Service\LogCleanupService:
    arguments:
        $loggingService: '@TerraFlow\Service\LoggingService'
        $logger: '@logger'
```

### Log-Konfiguration anpassen

```php
$loggingService = $container->get(LoggingService::class);

// Konfiguration abrufen
$config = $loggingService->getLogConfig();

// Konfiguration anpassen
$loggingService->setLogConfig([
    'max_file_size' => 20 * 1024 * 1024, // 20MB
    'max_files' => 10,
    'date_format' => 'Y-m-d H:i:s'
]);
```

## Admin-Commands

### Log-Bereinigung

```bash
# Log-Statistiken anzeigen
php bin/console terraflow:logs:cleanup --stats

# Vollständige Bereinigung
php bin/console terraflow:logs:cleanup

# Log-Rotation
php bin/console terraflow:logs:cleanup --rotate

# Kompression alter Logs
php bin/console terraflow:logs:cleanup --compress

# Ohne Bestätigung
php bin/console terraflow:logs:cleanup --force
```

### Log-Anzeige

```bash
# Verfügbare Log-Dateien auflisten
php bin/console terraflow:logs:view --list

# Log-Datei anzeigen
php bin/console terraflow:logs:view app.log

# Letzte 100 Zeilen
php bin/console terraflow:logs:view app.log --lines=100

# Nach Begriff filtern
php bin/console terraflow:logs:view app.log --grep="ERROR"

# Nach Log-Level filtern
php bin/console terraflow:logs:view app.log --level=error

# Log-Datei in Echtzeit verfolgen
php bin/console terraflow:logs:view app.log --follow
```

## Log-Struktur

### Automatischer Kontext

Jeder Log-Eintrag wird automatisch mit folgenden Informationen angereichert:

```php
[
    'user_id' => 123,                    // Aktueller Benutzer
    'username' => 'admin',               // Benutzername
    'ip_address' => '192.168.1.1',      // Client-IP
    'user_agent' => 'Mozilla/5.0...',   // Browser-Info
    'request_uri' => '/admin/pages',     // Request-URI
    'request_method' => 'POST',          // HTTP-Methode
    'memory_usage' => 1234567,           // Speicherverbrauch
    'request_id' => 'req_abc123',        // Eindeutige Request-ID
    'timestamp' => '2024-01-20 15:30:45' // Zeitstempel
]
```

### Log-Typen

Das System unterscheidet verschiedene Log-Typen:

- **user_action**: Benutzer-Aktionen
- **plugin_action**: Plugin-Aktionen
- **system_action**: System-Aktionen
- **database_action**: Datenbank-Operationen
- **api_request**: API-Anfragen
- **api_response**: API-Antworten
- **security_event**: Sicherheits-Ereignisse
- **performance**: Performance-Messungen
- **cache_operation**: Cache-Operationen
- **file_operation**: Datei-Operationen

## Best Practices

### Für Core-Entwicklung

- **Bereits angebunden:** `LoggingService` / `LoggingInterface` — unverändert nutzen; Level und Dateiausgabe folgen `monolog.yaml`.
- **Neuer Code:** bevorzugt `LoggerInterface` mit sinnvollem Kanal (TerraFlow: Kanal `terraflow` wie beim `LoggingService`) statt `dump()` / `error_log`.

```php
// Gute Logging-Praxis
$loggingService->logUserAction('page_created', [
    'page_id' => $page->getId(),
    'page_title' => $page->getTitle(),
    'route' => $page->getRoute()
]);

// Performance-Monitoring
$startTime = microtime(true);
$result = $this->expensiveOperation();
$executionTime = microtime(true) - $startTime;
$loggingService->logPerformance('expensive_operation', $executionTime, [
    'input_size' => count($input),
    'result_size' => count($result)
]);
```

### Für Plugin-Entwicklung

```php
// Plugin-Aktivierung
$this->logPluginAction('plugin_activated', [
    'version' => $this->getPluginInfo()->getVersion(),
    'dependencies' => $this->getDependencies()
]);

// Fehlerbehandlung
try {
    $this->processData($data);
} catch (\Exception $e) {
    $this->log('error', 'Plugin-Fehler bei Datenverarbeitung', [
        'error' => $e->getMessage(),
        'data_size' => count($data),
        'plugin_version' => $this->getPluginInfo()->getVersion()
    ]);
    throw $e;
}
```

## Log-Dateien

### Von Monolog geschriebene Dateien (Standard)

- **`dev.log`** (nur `APP_ENV=dev`): alle Kanäle außer `event` ab **DEBUG**
- **`prod.log`** (nur `APP_ENV=prod`): Rotation, ab **INFO**, ohne `event` und `deprecation`
- **`deprecation.log`** (prod): nur Kanal `deprecation`

Zusätzlich können **Symfony** oder Bundles weitere Dateien unter `var/log/` anlegen. Eigenes **Datei-Splitting** nach `error.log` / `plugin.log` erfolgt über `LogCleanupService`/Commands, sofern konfiguriert — die Monolog-Standardpfade oben sind die primäre Referenz.

### Log-Rotation

- **Maximale Dateigröße**: 10MB (konfigurierbar)
- **Maximale Anzahl**: 5 Dateien (konfigurierbar)
- **Automatische Rotation**: Bei Überschreitung der Größe
- **Kompression**: Alte Logs werden automatisch komprimiert

## Sicherheit

### Sensible Daten

Das Logging-System filtert automatisch sensible Daten:

```php
// Passwörter werden nicht geloggt
$loggingService->logUserAction('user_login', [
    'username' => 'admin',
    'password' => '[FILTERED]'  // Automatisch gefiltert
]);

// API-Keys werden maskiert
$loggingService->logApiRequest('/api/data', 'GET', [
    'api_key' => 'sk_***masked***'
]);
```

### IP-Adressen

IP-Adressen werden automatisch erfasst und können für Sicherheitsanalysen verwendet werden:

```php
$loggingService->logSecurityEvent('failed_login', [
    'username' => 'admin',
    'ip_address' => '192.168.1.1',
    'attempts' => 3
]);
```

## Monitoring und Alerting

### Performance-Überwachung

```php
// Langsame Operationen automatisch loggen
$loggingService->logPerformance('database_query', 2.5, [
    'query' => 'SELECT * FROM large_table',
    'rows_affected' => 10000
]);
```

### Fehler-Monitoring

```php
// Kritische Fehler sofort loggen
$loggingService->critical('Database connection lost', [
    'host' => 'localhost',
    'database' => 'terraflow',
    'error' => $e->getMessage()
]);
```

Das TerraFlowCMS Logging-System bietet eine umfassende Lösung für alle Logging-Anforderungen und ist vollständig in das Plugin-System integriert.
