1- import datetime
21import os
3- import queue
4- import threading
5- from typing import Optional , Dict , Any
2+ from typing import Optional
63
74from tinydb import TinyDB
85
6+ from .base_logger import BaseBusinessLogger
97
10- class JsonBusinessLogger :
11- _instance = None
12- _lock = threading .Lock ()
13- _GREEN = "\033 [92m"
14- _RESET = "\033 [0m"
158
16- def __new__ (cls , * args , ** kwargs ):
17- if not cls ._instance :
18- with cls ._lock :
19- if not cls ._instance :
20- cls ._instance = super ().__new__ (cls )
21- return cls ._instance
9+ class JsonBusinessLogger (BaseBusinessLogger ):
10+ # --- Définition des propriétés abstraites ---
11+ @property
12+ def logger_name (self ) -> str :
13+ return "EVENT-JSON"
2214
23- def __init__ (self ):
24- if not hasattr (self , '_initialized_flag' ):
25- self ._initialized_flag = False
26- self .is_enabled = False
27- self ._init_lock = threading .Lock ()
28- self .db : Optional [TinyDB ] = None
15+ @property
16+ def enabled_env_var (self ) -> str :
17+ return "JSON_BUSINESS_LOGGER_ENABLED"
2918
30- def _lazy_initialize ( self ):
31- with self . _init_lock :
32- if self . _initialized_flag : return
19+ @ property
20+ def db_file_env_var ( self ) -> str :
21+ return "JSON_BUSINESS_LOGGER_DB_FILE"
3322
34- enabled = os .getenv ("JSON_BUSINESS_LOGGER_ENABLED" , "false" ).lower () in ("true" , "1" , "yes" )
35- db_file = os .getenv ("JSON_BUSINESS_LOGGER_DB_FILE" )
23+ # --- Implémentation des méthodes abstraites ---
24+ def _setup_backend (self , db_file : str ) -> bool :
25+ self .db : Optional [TinyDB ] = None
26+ try :
27+ os .makedirs (os .path .dirname (db_file ), exist_ok = True )
28+ self .db = TinyDB (db_file , indent = 2 , ensure_ascii = False )
29+ return True
30+ except Exception as e :
31+ print (f"❌ Erreur lors de l'initialisation de { self .logger_name } : { e } " )
32+ return False
3633
37- if enabled and db_file :
38- try :
39- os .makedirs (os .path .dirname (db_file ), exist_ok = True )
40- self .db = TinyDB (db_file , indent = 2 , ensure_ascii = False )
41- self .is_enabled = True
42- self .log_queue = queue .Queue ()
43- self .worker_thread = threading .Thread (target = self ._process_queue , daemon = True )
44- self .worker_thread .start ()
45- print (f"✅ JsonBusinessLogger auto-configuré. Logs dans '{ db_file } '." )
46- except Exception as e :
47- print (f"❌ Erreur lors de l'initialisation de JsonBusinessLogger : { e } " )
48- self .is_enabled = False
34+ def _write_log_to_backend (self , log_item : dict ):
35+ if self .db :
36+ self .db .insert (log_item )
4937
50- self ._initialized_flag = True
51-
52- def _process_queue (self ):
53- while True :
54- try :
55- log_item = self .log_queue .get ()
56- if log_item is None : break
57- if self .db : self .db .insert (log_item )
58- self .log_queue .task_done ()
59- except Exception as e :
60- print (f"❌ Erreur dans le worker JsonBusinessLogger : { e } " )
61-
62- def log (self , event_type : str , details : Optional [Dict [str , Any ]] = None ):
63- if not self ._initialized_flag : self ._lazy_initialize ()
64- if not self .is_enabled : return
65-
66- details_str = f"- { details } " if details else ""
67- console_output = f"[EVENT-JSON] { event_type } { details_str } "
68- print (f"{ self ._GREEN } { console_output } { self ._RESET } " )
69-
70- log_document = {
71- 'timestamp' : datetime .datetime .now (datetime .timezone .utc ).isoformat (),
72- 'event_type' : event_type ,
73- 'details' : details
74- }
75- self .log_queue .put (log_document )
76-
77- def shutdown (self , wait = True ):
78- if not self ._initialized_flag : self ._lazy_initialize ()
79- if not self .is_enabled or not hasattr (self , 'log_queue' ): return
80- if wait : self .log_queue .join ()
81- self .log_queue .put (None )
82- if hasattr (self , 'worker_thread' ): self .worker_thread .join (timeout = 5 )
83- if self .db : self .db .close ()
84- print ("✅ JsonBusinessLogger arrêté proprement." )
85-
86- def __enter__ (self ):
87- return self
88-
89- def __exit__ (self , exc_type , exc_value , traceback ):
90- self .shutdown ()
38+ def _shutdown_backend (self ):
39+ if self .db :
40+ self .db .close ()
9141
9242
43+ # --- L'instance singleton reste la même ---
9344json_business_logger = JsonBusinessLogger ()
0 commit comments