Files

105 lines
3.6 KiB
Python

"""
Transaktionslogging für CMBNet
"""
import json
from datetime import datetime
from pathlib import Path
from threading import Lock
from flask import current_app
_WS_DEBUG_LOCK = Lock()
_FCM_DEBUG_LOCK = Lock()
def write_transaction_log(tenant_id, actor_id, actor_name, action, entity_type, entity_id, details=None):
"""
Schreibt einen lesbaren Eintrag ins tägliche Logfile
"""
log_dir = Path(current_app.config['LOG_DIR'])
log_dir.mkdir(parents=True, exist_ok=True)
date_str = datetime.now().strftime('%Y-%m-%d')
log_file = log_dir / f'cmbnet-{date_str}.log'
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
actor_str = f"{actor_id}({actor_name})" if actor_id and actor_name else "SYSTEM"
if isinstance(details, dict):
details_str = str(details)
elif details is None:
details_str = "{}"
else:
details_str = str(details)
log_line = f"{timestamp} [TENANT:{get_tenant_code(tenant_id)}] [ACTOR:{actor_str}] ACTION:{action} ENTITY:{entity_type}:{entity_id} DETAILS:{details_str}\n"
with open(log_file, 'a', encoding='utf-8') as f:
f.write(log_line)
def write_ws_debug_log(tenant_id, payload):
"""Schreibt eine Broker-Debugzeile in ein separates Tageslog.
Die Ausgabe enthält die eingehende Nachricht und den vom Broker
ermittelten Empfängerkreis. Sie ist bewusst unabhängig von der
Flask-Logger-Konfiguration, damit sie auch im Produktivbetrieb über
``CMBNET_WS_DEBUG_MESSAGES`` gezielt verfügbar ist.
"""
if not current_app.config.get('WS_DEBUG_MESSAGES', True):
return
log_dir = Path(current_app.config['LOG_DIR'])
log_dir.mkdir(parents=True, exist_ok=True)
date_str = datetime.now().strftime('%Y-%m-%d')
log_file = log_dir / f'cmbnet-ws-{date_str}.log'
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
line = (
f'{timestamp} [TENANT:{tenant_id}] WS-IN '
f'{json.dumps(payload, ensure_ascii=False, default=str)}\n'
)
with _WS_DEBUG_LOCK:
with open(log_file, 'a', encoding='utf-8') as f:
f.write(line)
def write_fcm_debug_log(payload, tenant_id=None):
"""Schreibt FCM-Diagnosezeilen in ein separates Tageslog.
Die Flask-Logger-Ausgabe landet je nach Deployment nur in stdout,
journald oder im Gunicorn-Log. Für die Fehlersuche am Wake-Button ist
eine eigene Datei ``logs/cmbnet-fcm-YYYY-MM-DD.log`` hilfreicher. Die
Funktion ist bewusst unabhängig von der Logger-Konfiguration und kann
über ``CMBNET_FCM_DEBUG_LOG=0`` abgeschaltet werden.
"""
try:
if not current_app.config.get('FCM_DEBUG_LOG', True):
return
log_dir = Path(current_app.config['LOG_DIR'])
except Exception:
return
log_dir.mkdir(parents=True, exist_ok=True)
date_str = datetime.now().strftime('%Y-%m-%d')
log_file = log_dir / f'cmbnet-fcm-{date_str}.log'
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
tenant_part = f'[TENANT:{tenant_id}] ' if tenant_id is not None else ''
line = (
f'{timestamp} {tenant_part}FCM '
f'{json.dumps(payload, ensure_ascii=False, default=str)}\n'
)
with _FCM_DEBUG_LOCK:
with open(log_file, 'a', encoding='utf-8') as f:
f.write(line)
def get_tenant_code(tenant_id):
"""Holt den Tenant-Code für die Logausgabe"""
from cmbnet.db import get_db
db = get_db()
tenant = db.execute('SELECT code FROM tenants WHERE id = ?', (tenant_id,)).fetchone()
return tenant['code'] if tenant else str(tenant_id)