FCM: Diagnose in eigenes Tageslog schreiben
This commit is contained in:
1 parent
94d8db2e7c
commit
d2be8e0d69
7 files changed
+136
No files matched your search
@@ -6,6 +6,7 @@ import re
|
||||
from flask import Blueprint, current_app, g, jsonify, request, session
|
||||
|
||||
from cmbnet.auth import login_required, role_required
|
||||
from cmbnet.core.logging import write_fcm_debug_log
|
||||
from cmbnet.services.fcm_service import fcm_service, public_fcm_config
|
||||
from cmbnet.ws import broker, store
|
||||
from cmbnet.ws.client_types import normalize_client_type
|
||||
@@ -76,6 +77,13 @@ def register_push_token(**kwargs):
|
||||
'FCM-Token registriert: tenant=%s client=%s type=%s',
|
||||
g.tenant_id, client_id, client_type
|
||||
)
|
||||
write_fcm_debug_log({
|
||||
'event': 'token-registered',
|
||||
'client_id': client_id,
|
||||
'account_id': account_id,
|
||||
'client_type': client_type,
|
||||
'platform': _platform_name(data.get('platform')),
|
||||
}, tenant_id=g.tenant_id)
|
||||
return jsonify({'ok': True})
|
||||
|
||||
|
||||
@@ -136,6 +144,13 @@ def wake_mobile_clients(**kwargs):
|
||||
'FCM-Wake nicht möglich: tenant=%s tokens=%s grund=%s',
|
||||
g.tenant_id, stats['valid_tokens'], message
|
||||
)
|
||||
write_fcm_debug_log({
|
||||
'event': 'wake-unavailable',
|
||||
'group_id': group_id,
|
||||
'valid_tokens': stats['valid_tokens'],
|
||||
'connected': stats['connected'],
|
||||
'error': message,
|
||||
}, tenant_id=g.tenant_id)
|
||||
return jsonify({
|
||||
'ok': False,
|
||||
'configured': False,
|
||||
@@ -187,6 +202,17 @@ def wake_mobile_clients(**kwargs):
|
||||
'FCM-Wake-Fehler: tenant=%s token=%s error=%s',
|
||||
g.tenant_id, item.get('fingerprint'), item.get('error')
|
||||
)
|
||||
write_fcm_debug_log({
|
||||
'event': 'wake-manual',
|
||||
'group_id': group_id,
|
||||
'valid_tokens': stats['valid_tokens'],
|
||||
'connected': stats['connected'],
|
||||
'candidates': len(candidates),
|
||||
'sent': int(result.get('sent') or 0),
|
||||
'failed': int(result.get('failed') or 0),
|
||||
'errors': error_details,
|
||||
'error': result.get('error'),
|
||||
}, tenant_id=g.tenant_id)
|
||||
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
|
||||
@@ -9,6 +9,7 @@ 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):
|
||||
@@ -64,6 +65,37 @@ def write_ws_debug_log(tenant_id, payload):
|
||||
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
|
||||
|
||||
@@ -154,6 +154,7 @@ class FcmService:
|
||||
'Bitte requirements.txt installieren.'
|
||||
)
|
||||
logger.warning(self._error)
|
||||
self._log_debug({'event': 'init-error', 'error': self._error})
|
||||
return None, self._error
|
||||
|
||||
try:
|
||||
@@ -173,6 +174,7 @@ class FcmService:
|
||||
except Exception as exc:
|
||||
self._error = f'FCM-Initialisierung fehlgeschlagen: {exc}'
|
||||
logger.exception(self._error)
|
||||
self._log_debug({'event': 'init-error', 'error': self._error})
|
||||
return None, self._error
|
||||
|
||||
return self._app, None
|
||||
@@ -209,6 +211,22 @@ class FcmService:
|
||||
return f'{name}: {text}'
|
||||
return name
|
||||
|
||||
@staticmethod
|
||||
def _log_debug(payload):
|
||||
"""Schreibt eine FCM-Diagnosezeile in das separate FCM-Log."""
|
||||
tenant_id = None
|
||||
try:
|
||||
from flask import g
|
||||
tenant_id = getattr(g, 'tenant_id', None)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
from cmbnet.core.logging import write_fcm_debug_log
|
||||
write_fcm_debug_log(payload, tenant_id=tenant_id)
|
||||
except Exception:
|
||||
# Diagnose darf den Versand nie beeinflussen.
|
||||
pass
|
||||
|
||||
def send_wake(self, tokens, reason='wake'):
|
||||
"""Sendet ein reines Daten-Signal an die angegebenen FCM-Tokens.
|
||||
|
||||
@@ -232,6 +250,14 @@ class FcmService:
|
||||
app, error = self._ensure_app()
|
||||
if error or app is None:
|
||||
result['error'] = error
|
||||
self._log_debug({
|
||||
'event': 'wake',
|
||||
'reason': reason,
|
||||
'requested': len(tokens),
|
||||
'sent': 0,
|
||||
'failed': 0,
|
||||
'error': error,
|
||||
})
|
||||
return result
|
||||
|
||||
result['configured'] = True
|
||||
@@ -270,6 +296,15 @@ class FcmService:
|
||||
if batch_result.get('error'):
|
||||
result['error'] = batch_result['error']
|
||||
|
||||
self._log_debug({
|
||||
'event': 'wake',
|
||||
'reason': reason,
|
||||
'requested': len(tokens),
|
||||
'sent': result['sent'],
|
||||
'failed': result['failed'],
|
||||
'errors': result['errors'][:5],
|
||||
'error': result.get('error'),
|
||||
})
|
||||
return result
|
||||
|
||||
def _send_batch(self, messaging, tokens, data, android, webpush, app=None):
|
||||
@@ -300,6 +335,11 @@ class FcmService:
|
||||
'FCM-Batchversand fehlgeschlagen (%s Empfänger): %s',
|
||||
len(tokens), details
|
||||
)
|
||||
self._log_debug({
|
||||
'event': 'batch-error',
|
||||
'recipients': len(tokens),
|
||||
'error': details,
|
||||
})
|
||||
batch_result['failed'] += len(tokens)
|
||||
batch_result['error'] = details
|
||||
batch_result['errors'].append({
|
||||
@@ -321,6 +361,11 @@ class FcmService:
|
||||
'FCM-Signal abgelehnt: token=%s error=%s',
|
||||
fingerprint, details
|
||||
)
|
||||
self._log_debug({
|
||||
'event': 'rejected',
|
||||
'token': fingerprint,
|
||||
'error': details,
|
||||
})
|
||||
batch_result['errors'].append({
|
||||
'fingerprint': fingerprint,
|
||||
'error': details,
|
||||
|
||||
@@ -32,6 +32,7 @@ from datetime import datetime, timedelta, timezone
|
||||
from threading import Event, Lock
|
||||
from flask import current_app
|
||||
from cmbnet.db import get_db
|
||||
from cmbnet.core.logging import write_fcm_debug_log
|
||||
from cmbnet.services.fcm_service import fcm_service
|
||||
from cmbnet.services.groups_service import GroupsService
|
||||
from cmbnet.ws import store
|
||||
@@ -636,6 +637,16 @@ class WebSocketBroker:
|
||||
|
||||
tokens = [row['token'] for row in rows]
|
||||
result = fcm_service.send_wake(tokens, reason=reason)
|
||||
write_fcm_debug_log({
|
||||
'event': 'wake-auto',
|
||||
'client_id': client_id,
|
||||
'reason': reason,
|
||||
'tokens': len(tokens),
|
||||
'sent': int(result.get('sent') or 0),
|
||||
'failed': int(result.get('failed') or 0),
|
||||
'errors': list(result.get('errors') or [])[:5],
|
||||
'error': result.get('error'),
|
||||
}, tenant_id=tenant_id)
|
||||
for token in result.get('invalid_tokens') or []:
|
||||
store.mark_push_token_invalid(token)
|
||||
|
||||
|
||||
Reference in new issue
Block a user