template-python/app/logging_utils.py
Adam Skotarczak 39aacfa931 Initialer stabiler Stand
- Bootstrap mit .venv-Autoinstall und Relaunch
- Logging-Modul mit Loglevel-Fallback und optionaler Rotation
- .env-Support via python-dotenv
- Beispielstruktur für portable Python-Apps
- Umfangreiche README mit Anleitung und Logging-Kapitel
- .env.example enthalten
- VS Code-Tasks integriert
2025-04-23 12:05:52 +02:00

63 lines
1.8 KiB
Python
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.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Zentrales Logging-Modul
→ Unterstützt LOGLEVEL und LOGFILE aus der .env
→ Plattformunabhängig (Windows/Linux)
→ Erstellt automatisch das Log-Verzeichnis bei Bedarf
→ Fällt bei ungültigem Log-Level sicher auf INFO zurück
"""
import logging
import os
from logging.handlers import RotatingFileHandler
from pathlib import Path
def safe_log_level(level_str: str) -> int:
"""Wandelt einen Level-String in einen gültigen Logging-Level um."""
levels = {
"CRITICAL": logging.CRITICAL,
"ERROR": logging.ERROR,
"WARNING": logging.WARNING,
"INFO": logging.INFO,
"DEBUG": logging.DEBUG,
"NOTSET": logging.NOTSET,
}
return levels.get(level_str.upper(), logging.INFO)
LOGLEVEL = safe_log_level(os.getenv("LOGLEVEL", "INFO"))
LOGFILE = os.getenv("LOGFILE") # z.B. logs/app.log
def get_logger(name: str) -> logging.Logger:
logger = logging.getLogger(name)
if logger.handlers:
return logger # Logger bereits konfiguriert
logger.setLevel(LOGLEVEL)
formatter = logging.Formatter("[%(asctime)s] %(levelname)s %(name)s: %(message)s")
# Konsole
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
# Datei (optional)
if LOGFILE:
logfile_path = Path(LOGFILE)
try:
logfile_path.parent.mkdir(parents=True, exist_ok=True)
file_handler = RotatingFileHandler(
logfile_path, maxBytes=1_000_000, backupCount=3, encoding="utf-8"
)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
except Exception as e:
logger.warning(f"Konnte Logdatei nicht schreiben: {e}")
return logger