mkcontrol-app/app/utils/logging.py

88 lines
2.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

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.

# app/utils/logging.py
import logging
import os
import shutil
from logging.handlers import TimedRotatingFileHandler
from datetime import datetime, timedelta
LOG_DIR = app.config['LOG_DIR']
os.makedirs(LOG_DIR, exist_ok=True)
def cleanup_old_log_dirs(max_age_days=90):
"""
Löscht Monatsordner in logs/, die älter als max_age_days sind.
Beispiel: logs/2025-11/ wird gelöscht, wenn älter als 90 Tage.
"""
if not os.path.exists(LOG_DIR):
return
cutoff_date = datetime.now() - timedelta(days=max_age_days)
cutoff_str = cutoff_date.strftime('%Y-%m')
deleted = 0
for subdir in os.listdir(LOG_DIR):
subdir_path = os.path.join(LOG_DIR, subdir)
if os.path.isdir(subdir_path):
try:
subdir_date = datetime.strptime(subdir, '%Y-%m')
if subdir_date < cutoff_date:
shutil.rmtree(subdir_path)
deleted += 1
logger.info(f"Alten Log-Ordner gelöscht: {subdir_path}")
except ValueError:
# Kein gültiges Datumsformat → überspringen
continue
except Exception as e:
logger.error(f"Fehler beim Löschen von {subdir_path}: {e}")
if deleted > 0:
logger.info(f"Insgesamt {deleted} alte Log-Ordner bereinigt")
else:
logger.debug("Keine alten Log-Ordner zum Bereinigen gefunden")
def setup_logging(app):
"""
Richtet das Logging ein: tägliche Dateien in Unterordnern + Trennung info/error.
Ruft auch einmalig cleanup auf.
"""
# Cleanup beim Start
cleanup_old_log_dirs(90)
today = datetime.now().strftime('%Y-%m')
subdir = os.path.join(LOG_DIR, today)
os.makedirs(subdir, exist_ok=True)
base = os.path.join(subdir, datetime.now().strftime('%d'))
# Info-Handler
info_handler = logging.FileHandler(f"{base}-info.log")
info_handler.setLevel(logging.INFO)
info_handler.setFormatter(logging.Formatter(
'%(asctime)s | %(levelname)-8s | %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
))
# Error-Handler
error_handler = logging.FileHandler(f"{base}-error.log")
error_handler.setLevel(logging.WARNING)
error_handler.setFormatter(logging.Formatter(
'%(asctime)s | %(levelname)-8s | %(message)s\n%(pathname)s:%(lineno)d\n',
datefmt='%Y-%m-%d %H:%M:%S'
))
# Root-Logger konfigurieren
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.handlers.clear()
logger.addHandler(info_handler)
logger.addHandler(error_handler)
# Konsole
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(info_handler.formatter)
logger.addHandler(console)
logger.info("Logging eingerichtet tägliche Trennung info/error")
logger.info(f"Logs heute: {base}-info.log / {base}-error.log")