|
| 1 | +import datetime |
| 2 | +import json |
| 3 | +import os |
| 4 | +import queue |
| 5 | +import sqlite3 |
| 6 | +import threading |
| 7 | +from typing import Optional, Dict, Any |
| 8 | + |
| 9 | + |
| 10 | +class SqliteBusinessLogger: |
| 11 | + """ |
| 12 | + Un logger métier auto-configurable, thread-safe et non-bloquant. |
| 13 | + Il s'initialise automatiquement à partir des variables d'environnement |
| 14 | + lors de sa première utilisation. |
| 15 | + """ |
| 16 | + _instance = None |
| 17 | + _lock = threading.Lock() |
| 18 | + |
| 19 | + _GREEN = "\033[92m" |
| 20 | + _RESET = "\033[0m" |
| 21 | + |
| 22 | + def __new__(cls, *args, **kwargs): |
| 23 | + if not cls._instance: |
| 24 | + with cls._lock: |
| 25 | + if not cls._instance: |
| 26 | + cls._instance = super().__new__(cls) |
| 27 | + return cls._instance |
| 28 | + |
| 29 | + def __init__(self): |
| 30 | + if not hasattr(self, '_initialized_flag'): |
| 31 | + self._initialized_flag = False |
| 32 | + self.is_enabled = False |
| 33 | + self._init_lock = threading.Lock() |
| 34 | + |
| 35 | + def _lazy_initialize(self): |
| 36 | + """ |
| 37 | + Effectue l'initialisation une seule fois, de manière thread-safe. |
| 38 | + """ |
| 39 | + with self._init_lock: |
| 40 | + if self._initialized_flag: |
| 41 | + return |
| 42 | + |
| 43 | + enabled = os.getenv("BUSINESS_LOGGER_ENABLED", "false").lower() in ("true", "1", "yes") |
| 44 | + db_file = os.getenv("BUSINESS_LOGGER_DB_FILE") |
| 45 | + |
| 46 | + if enabled and db_file: |
| 47 | + self.is_enabled = True |
| 48 | + self.db_file = db_file |
| 49 | + self.table_name = os.getenv("BUSINESS_LOGGER_TABLE_NAME", "business_events") |
| 50 | + self.log_queue = queue.Queue() |
| 51 | + self._create_table() |
| 52 | + self.worker_thread = threading.Thread(target=self._process_queue, daemon=True) |
| 53 | + self.worker_thread.start() |
| 54 | + print(f"✅ BusinessLogger auto-configuré. Logs dans '{self.db_file}'.") |
| 55 | + |
| 56 | + self._initialized_flag = True |
| 57 | + |
| 58 | + def _create_table(self): |
| 59 | + """Crée la table de la base de données si elle n'existe pas.""" |
| 60 | + try: |
| 61 | + path_dirname = os.path.dirname(self.db_file) |
| 62 | + if len(path_dirname) > 0: |
| 63 | + os.makedirs(path_dirname, exist_ok=True) |
| 64 | + with sqlite3.connect(self.db_file) as conn: |
| 65 | + cursor = conn.cursor() |
| 66 | + cursor.execute(f""" |
| 67 | + CREATE TABLE IF NOT EXISTS {self.table_name} ( |
| 68 | + id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 69 | + timestamp TEXT NOT NULL, |
| 70 | + event_type TEXT NOT NULL, |
| 71 | + details_json TEXT |
| 72 | + ) |
| 73 | + """) |
| 74 | + conn.commit() |
| 75 | + except Exception as e: |
| 76 | + print(f"❌ Erreur lors de la création de la table pour BusinessLogger : {e}") |
| 77 | + self.is_enabled = False |
| 78 | + |
| 79 | + def _process_queue(self): |
| 80 | + """Méthode exécutée par le thread de travail pour écrire en BDD.""" |
| 81 | + with sqlite3.connect(self.db_file, check_same_thread=False) as conn: |
| 82 | + cursor = conn.cursor() |
| 83 | + while True: |
| 84 | + try: |
| 85 | + log_item = self.log_queue.get() |
| 86 | + if log_item is None: |
| 87 | + break |
| 88 | + |
| 89 | + timestamp, event_type, details = log_item |
| 90 | + details_json = json.dumps(details) if details else None |
| 91 | + |
| 92 | + cursor.execute( |
| 93 | + f"INSERT INTO {self.table_name} (timestamp, event_type, details_json) VALUES (?, ?, ?)", |
| 94 | + (timestamp, event_type, details_json) |
| 95 | + ) |
| 96 | + conn.commit() |
| 97 | + self.log_queue.task_done() |
| 98 | + except Exception as e: |
| 99 | + print(f"❌ Erreur dans le worker BusinessLogger : {e}") |
| 100 | + |
| 101 | + def log(self, event_type: str, details: Optional[Dict[str, Any]] = None): |
| 102 | + """ |
| 103 | + Enregistre un événement métier. S'initialise au premier appel. |
| 104 | + Imprime également le log en vert sur la console. |
| 105 | + """ |
| 106 | + if not self._initialized_flag: |
| 107 | + self._lazy_initialize() |
| 108 | + |
| 109 | + if not self.is_enabled: |
| 110 | + return |
| 111 | + |
| 112 | + timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat() |
| 113 | + |
| 114 | + details_str = f"- {details}" if details else "" |
| 115 | + console_output = f"[EVENT] {event_type} {details_str}" |
| 116 | + print(f"{self._GREEN}{console_output}{self._RESET}") |
| 117 | + |
| 118 | + # La logique existante pour la mise en file d'attente reste inchangée |
| 119 | + self.log_queue.put((timestamp, event_type, details)) |
| 120 | + |
| 121 | + def shutdown(self, wait=True): |
| 122 | + """Arrête proprement le logger.""" |
| 123 | + if not self._initialized_flag: |
| 124 | + self._lazy_initialize() |
| 125 | + |
| 126 | + if not self.is_enabled or not hasattr(self, 'log_queue'): |
| 127 | + return |
| 128 | + |
| 129 | + if wait: |
| 130 | + self.log_queue.join() |
| 131 | + |
| 132 | + self.log_queue.put(None) |
| 133 | + if hasattr(self, 'worker_thread'): |
| 134 | + self.worker_thread.join(timeout=5) |
| 135 | + print("✅ BusinessLogger arrêté proprement.") |
| 136 | + |
| 137 | + |
| 138 | +# L'instance singleton est créée, mais pas encore configurée. |
| 139 | +sqlite_business_logger = SqliteBusinessLogger() |
0 commit comments