reorg ini e log

This commit is contained in:
2025-05-13 22:48:08 +02:00
parent 12ac522b98
commit 976116e2f3
32 changed files with 136 additions and 60 deletions

View File

@@ -5,21 +5,21 @@ import mysql.connector
import logging
import importlib
import asyncio
import os
# Import custom modules for configuration and database connection
from utils.config import loader as setting
from utils.config import loader_load_data as setting
from utils.database.connection import connetti_db
from utils.database.loader_action import CSV_RECEIVED
# Initialize the logger for this module
logger = logging.getLogger(__name__)
logger = logging.getLogger()
# Delay tra un processamento CSV e il successivo (in secondi)
CSV_PROCESSING_DELAY = 0.1
# Tempo di attesa se non ci sono record da elaborare
NO_RECORD_SLEEP = 20
async def worker(worker_id: int, queue: asyncio.Queue, cfg: object) -> None:
"""
Worker asyncrono che preleva lavori dalla coda e li esegue.
@@ -29,6 +29,7 @@ async def worker(worker_id: int, queue: asyncio.Queue, cfg: object) -> None:
queue (asyncio.Queue): Coda da cui prendere i lavori.
cfg (object): Configurazione caricata.
"""
debug_mode = (logging.getLogger().getEffectiveLevel() == logging.DEBUG)
logger.info(f"Worker {worker_id} - Avviato")
while True:
@@ -48,12 +49,12 @@ async def worker(worker_id: int, queue: asyncio.Queue, cfg: object) -> None:
await asyncio.sleep(CSV_PROCESSING_DELAY)
else:
logger.debug(f"Worker {worker_id} - Elaborazione completata correttamente")
await asyncio.sleep(CSV_PROCESSING_DELAY)
await asyncio.sleep(CSV_PROCESSING_DELAY*worker_id)
# Segnala che il lavoro è completato
queue.task_done()
except Exception as e:
logger.error(f"Worker {worker_id} - Errore durante l'esecuzione: {e}", exc_info=True)
logger.error(f"Worker {worker_id} - Errore durante l'esecuzione: {e}", exc_info=debug_mode)
queue.task_done()
@@ -67,6 +68,8 @@ async def load_csv(cfg: object) -> tuple:
Returns:
bool: True se è stato trovato ed elaborato un record, False altrimenti.
"""
debug_mode = (logging.getLogger().getEffectiveLevel() == logging.DEBUG)
logger.debug("Inizio ricerca nuovo CSV da elaborare")
try:
@@ -107,14 +110,14 @@ async def load_csv(cfg: object) -> tuple:
logger.info(f"Elaborazione completata per ID={id}")
return True, True
except (ImportError, AttributeError) as e:
logger.error(f"Errore nel caricamento del modulo o della funzione: {e}", exc_info=True)
logger.error(f"Errore nel caricamento del modulo o della funzione: {e}", exc_info=debug_mode)
return True, False
else:
logger.debug("Nessun record disponibile per l'elaborazione")
return False, False
except mysql.connector.Error as e:
logger.error(f"Errore di database: {e}", exc_info=True)
logger.error(f"Errore di database: {e}", exc_info=debug_mode)
return False, False
@@ -127,15 +130,18 @@ async def main():
try:
# Configura il logging globale
log_level = os.getenv("LOG_LEVEL", "INFO").upper()
debug_mode = (logging.getLogger().getEffectiveLevel() == logging.DEBUG)
logging.basicConfig(
format="%(asctime)s - PID: %(process)d.%(name)s.%(levelname)s: %(message)s ",
filename=cfg.logfilename,
level=logging.INFO,
level=log_level,
)
logger.info("Logging configurato correttamente")
# Crea una coda di lavoro illimitata
queue = asyncio.Queue(maxsize=cfg.queue_maxsize or 10)
queue = asyncio.Queue(maxsize=cfg.max_threads * 2 or 20)
logger.debug("Coda di lavoro creata")
# Numero massimo di worker concorrenti
@@ -169,12 +175,12 @@ async def main():
for task in workers:
task.cancel()
await asyncio.gather(*workers, return_exceptions=True)
await asyncio.gather(*workers, return_exceptions=debug_mode)
logger.info("Info: Tutti i task terminati. Uscita.")
except Exception as e:
logger.error(f"Errore principale: {e}", exc_info=True)
logger.error(f"Errore principale: {e}", exc_info=debug_mode)
if __name__ == "__main__":