Projektarbeit-MYP/backend/docs/LOGGING_README.md
2025-05-31 22:40:29 +02:00

322 lines
6.8 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 📊 MYP Logging & Debug System
## 🚀 Übersicht
Das MYP (Manage Your Printers) System verfügt über ein umfassendes, verbessertes Logging- und Debug-System mit modernen Features wie:
- 🎨 **Farbige Konsolen-Ausgaben** mit ANSI-Unterstützung
- 😀 **Emoji-Integration** für bessere Lesbarkeit
- ⏱️ **Performance-Monitoring** mit Ausführungszeit-Messung
- 🌐 **HTTP-Request/Response-Logging** für API-Debugging
- 💻 **Cross-Platform-Unterstützung** (Windows/Unix/Linux)
- 🔍 **Strukturierte Debug-Informationen** mit erweiterten Metadaten
## 📁 Struktur
```
utils/
├── logging_config.py # Haupt-Logging-Konfiguration
├── debug_utils.py # Debug-Hilfsfunktionen
debug_cli.py # Kommandozeilen-Debug-Tool
```
## 🎨 Features im Detail
### 1. Farbige Log-Ausgaben
Das System verwendet ANSI-Farbcodes für verschiedene Log-Level:
- 🔍 **DEBUG**: Cyan
- **INFO**: Grün
- ⚠️ **WARNING**: Gelb
-**ERROR**: Rot
- 🔥 **CRITICAL**: Roter Hintergrund mit weißem Text
### 2. Emoji-Integration
Emojis werden automatisch basierend auf Log-Level und Kategorie hinzugefügt:
**Log-Level:**
- 🔍 DEBUG
- INFO
- ⚠️ WARNING
- ❌ ERROR
- 🔥 CRITICAL
**Kategorien:**
- 🖥️ app
- ⏱️ scheduler
- 🔐 auth
- 🖨️ jobs
- 🔧 printers
- 💥 errors
- 👤 user
- 📺 kiosk
### 3. Performance-Monitoring
```python
from utils.logging_config import measure_execution_time, get_logger
# Als Dekorator verwenden
@measure_execution_time(logger=get_logger("app"), task_name="Drucker-Scan")
def scan_printer():
# Ihre Funktion hier
pass
# Als Context-Manager verwenden
from utils.debug_utils import debug_timer
with debug_timer("Datenbankabfrage"):
# Ihr Code hier
pass
```
### 4. HTTP-Request/Response-Logging
Automatisches Logging aller HTTP-Anfragen und -Antworten:
```python
# Wird automatisch für alle API-Endpunkte (/api/*) aktiviert
# Loggt:
# - Request-Method, URL, Headers, Parameter
# - Response-Status, Größe, Ausführungszeit
# - Client-IP und User-Agent
```
## 🛠️ Verwendung
### Basis-Logging
```python
from utils.logging_config import get_logger
# Logger für verschiedene Komponenten erstellen
app_logger = get_logger("app")
auth_logger = get_logger("auth")
jobs_logger = get_logger("jobs")
# Verwenden
app_logger.info("🚀 Anwendung gestartet")
auth_logger.warning("⚠️ Fehlgeschlagener Login-Versuch")
```
### Debug-Funktionen
```python
from utils.debug_utils import debug_dump, debug_trace, debug_function
# Objekt-Debugging
debug_dump(my_object, "Drucker-Konfiguration")
# Stack-Trace ausgeben
debug_trace("Checkpoint erreicht")
# Funktion automatisch debuggen
@debug_function(level=DebugLevel.VERBOSE)
def my_function():
pass
```
### Memory-Monitoring
```python
from utils.debug_utils import memory_usage, log_memory_usage
# Speicherverbrauch messen
memory_info = memory_usage()
print(f"RAM: {memory_info['rss']:.2f} MB")
# Automatisch loggen
log_memory_usage("Meine Anwendung")
```
## 🖥️ Debug-CLI
Das erweiterte Debug-CLI bietet mehrere Befehle:
```bash
# Vollständige Diagnose
python debug_cli.py diagnose
# Drucker scannen
python debug_cli.py scan
# API-Routen anzeigen
python debug_cli.py routes
# Systeminformationen
python debug_cli.py sysinfo
# Log-Dateien analysieren
python debug_cli.py logs
# Logging-System testen
python debug_cli.py test-logging
```
### Interaktives Menü
Starten Sie das CLI ohne Parameter für ein interaktives Menü:
```bash
python debug_cli.py
```
## ⚙️ Konfiguration
### Log-Level setzen
```python
from utils.logging_config import setup_logging
# Debug-Modus aktivieren
setup_logging(debug_mode=True)
# Standard-Logging
setup_logging(debug_mode=False)
```
### Debug-Level für Debug-Utils
```python
from utils.debug_utils import set_debug_level, DebugLevel
# Debug-Level setzen
set_debug_level(DebugLevel.VERBOSE) # 0=MINIMAL, 1=NORMAL, 2=VERBOSE, 3=TRACE
```
### Windows-Unterstützung
Das System aktiviert automatisch VT100-Unterstützung unter Windows für Farbausgaben:
```python
# Automatische Aktivierung in logging_config.py
import ctypes
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
```
## 📊 Ausgabe-Beispiele
### Startup-Logs
```
🚀 =================== MYP WIRD GESTARTET ===================
🖥️ [INFO] 📂 Log-Verzeichnis: ./logs
🖥️ [INFO] 📊 Log-Level: INFO
🖥️ [INFO] 💻 Betriebssystem: Windows 10
🖥️ [INFO] 🌐 Hostname: MYP-SERVER
🖥️ [INFO] 📅 Startzeit: 15.12.2024 14:30:00
🖥️ ========================================================
```
### HTTP-Request-Logs
```
🔍 [DEBUG] 🌐 HTTP-Anfrage: GET /api/printers
🔍 [DEBUG] 📡 Remote-Adresse: 192.168.1.100
🔍 [DEBUG] 🧩 Inhaltstyp: application/json
✅ [DEBUG] ✅ HTTP-Antwort: 200
🔍 [DEBUG] ⏱️ Verarbeitungsdauer: 45.23 ms
🔍 [DEBUG] 📦 Antwortgröße: 2.1 KB
```
### Performance-Monitoring
```
🔍 [DEBUG] ⏱️ Ausführungszeit: Drucker-Status-Prüfung - 234.56 ms
⚠️ [WARNING] ⏱️ Langsame Ausführung: API-Live-Drucker-Status - 1234.56 ms
```
## 🔧 Erweiterte Features
### Error-Handling mit automatischem Logging
```python
from utils.debug_utils import debug_exception_handler
@debug_exception_handler(logger=get_logger("app"))
def risky_function():
# Code der Exceptions werfen könnte
pass
```
### Profiling
```python
from utils.debug_utils import profile_function
@profile_function
def performance_critical_function():
# Wird automatisch profiliert
pass
```
### Cache-Clearing
```python
# API-Endpunkte zum Cache-Clearing
POST /api/printers/cache/clear
POST /api/admin/cache/clear
```
## 📈 Monitoring & Wartung
### Log-Rotation
- Automatische Rotation bei 10 MB Dateigröße
- 5 Backup-Dateien werden behalten
- Separate Log-Dateien für verschiedene Komponenten
### Backup & Cleanup
```python
# Automatische Backups über backup_manager
# Cleanup über maintenance_scheduler
```
## 🔍 Troubleshooting
### Farben funktionieren nicht
1. Prüfen Sie die Terminal-Unterstützung:
```python
from utils.logging_config import supports_color
print(supports_color())
```
2. Windows: Stellen Sie sicher, dass VT100-Modus aktiviert ist
### Performance-Issues
1. Debug-Level reduzieren:
```python
set_debug_level(DebugLevel.MINIMAL)
```
2. HTTP-Logging für Produktion deaktivieren:
```python
# In app.py die before_request/after_request Handler modifizieren
```
### Memory-Leaks
1. Memory-Monitoring aktivieren:
```python
log_memory_usage("Komponente")
```
2. Debug-Utils für Speicher-Profiling nutzen
## 📞 Support
Bei Problemen oder Fragen:
1. Debug-CLI verwenden: `python debug_cli.py test-logging`
2. Log-Dateien prüfen: `python debug_cli.py logs`
3. Vollständige Diagnose: `python debug_cli.py diagnose`
---
*Erstellt für MYP v1.0.0 - Manage Your Printers* 🖨️