fix for logger

This commit is contained in:
Andreas Knuth 2026-02-09 15:59:29 -06:00
parent 88d526aa00
commit 3849e3fc2d
1 changed files with 34 additions and 34 deletions

View File

@ -1,6 +1,6 @@
#!/usr/bin/env python3
"""
Structured logging for email worker with Daily Rotation
Structured logging for email worker with Daily Rotation (Robust Version)
"""
import os
@ -8,7 +8,6 @@ import sys
import logging
import threading
from logging.handlers import TimedRotatingFileHandler
from datetime import datetime
# Konfiguration
LOG_DIR = "/var/log/email-worker"
@ -19,24 +18,22 @@ logger = logging.getLogger("unified-worker")
logger.setLevel(logging.INFO)
logger.propagate = False
# Formatierung definieren: [Timestamp] [Level] [Thread] Nachricht
# Hinweis: worker_name wird in der Funktion 'log' manuell eingefügt
# Formatierung
formatter = logging.Formatter(
'[%(asctime)s] [%(levelname)s] [%(threadName)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# 1. Console Handler (damit 'docker logs' weiterhin etwas anzeigt)
# 1. Console Handler (Immer aktiv!)
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
# 2. File Handler mit täglicher Rotation
# Prüfen, ob das Verzeichnis schreibbar ist (durch Docker Volume Mount)
if os.path.exists(LOG_DIR):
# 2. File Handler (Robustes Setup)
try:
# when="midnight": Rotiert jede Nacht um 00:00 Uhr
# backupCount=30: Behält Logs für 30 Tage
# Versuchen, das Verzeichnis zu erstellen, falls es fehlt
os.makedirs(LOG_DIR, exist_ok=True)
file_handler = TimedRotatingFileHandler(
LOG_FILE,
when="midnight",
@ -45,35 +42,38 @@ if os.path.exists(LOG_DIR):
encoding='utf-8'
)
file_handler.setFormatter(formatter)
# Suffix für rotierte Dateien: worker.log.2023-10-27
file_handler.suffix = "%Y-%m-%d"
logger.addHandler(file_handler)
# Erfolgsmeldung auf Konsole (damit wir sehen, dass es geklappt hat)
print(f"✓ Logging to file enabled: {LOG_FILE}")
except Exception as e:
print(f"⚠ Logging Setup Error: Could not create file handler: {e}")
# Fallback: Ausführliche Fehlerdiagnose auf stdout
error_msg = f"⚠ LOGGING ERROR: Could not write to {LOG_FILE}\n"
error_msg += f" Error: {e}\n"
try:
error_msg += f" Current User (UID): {os.getuid()}\n"
error_msg += f" Current Group (GID): {os.getgid()}\n"
except:
pass
print(error_msg)
def log(message: str, level: str = 'INFO', worker_name: str = 'unified-worker'):
"""
Structured logging with timestamp and thread info.
Drop-In Replacement for original print-based logging.
Structured logging function
"""
# Mapping von String-Levels zu logging Konstanten
lvl_map = {
'DEBUG': logging.DEBUG,
'INFO': logging.INFO,
'WARNING': logging.WARNING,
'ERROR': logging.ERROR,
'CRITICAL': logging.CRITICAL,
'SUCCESS': logging.INFO # 'SUCCESS' gibt es im Standard nicht, wir nutzen INFO
'SUCCESS': logging.INFO
}
log_level = lvl_map.get(level.upper(), logging.INFO)
# Prefix für SUCCESS Level manuell hinzufügen, da es im Standard-Logging fehlt
prefix = ""
if level.upper() == 'SUCCESS':
prefix = "[SUCCESS] "
# Den worker_name in die Nachricht integrieren
prefix = "[SUCCESS] " if level.upper() == 'SUCCESS' else ""
final_message = f"[{worker_name}] {prefix}{message}"
logger.log(log_level, final_message)