Uecko_ERP_FactuGES_sync/app/config/setup_logger.py

86 lines
2.3 KiB
Python
Raw Permalink Normal View History

2025-11-30 22:44:55 +00:00
from __future__ import annotations
2025-11-30 18:28:44 +00:00
import logging
import os
2025-11-30 22:44:55 +00:00
import sys
2025-11-30 18:28:44 +00:00
from logging.handlers import RotatingFileHandler
from pathlib import Path
2025-11-30 22:44:55 +00:00
from typing import Optional, Union
2025-11-30 18:28:44 +00:00
def create_logger(
name: str = "factuges-sync",
*,
level: int = logging.INFO,
2025-11-30 22:44:55 +00:00
log_path: Optional[Union[str, Path]] = None,
max_bytes: int = 5_000_000, # rotación opcional
backup_count: int = 3,
2025-11-30 18:28:44 +00:00
) -> logging.Logger:
"""
2025-11-30 22:44:55 +00:00
Crea un logger consistente para FactuGES Sync.
Reglas:
- SIEMPRE envia logs a stdout (Docker-friendly).
- SOLO en producción escribe también a fichero si `log_path` está definido.
- `log_path` puede ser `str` o `Path`.
- Evita duplicar handlers.
2025-11-30 18:28:44 +00:00
"""
logger = logging.getLogger(name)
logger.setLevel(level)
2025-11-30 22:44:55 +00:00
# Si ya está configurado, no duplicamos handlers
2025-11-30 18:28:44 +00:00
if logger.handlers:
return logger
2025-11-30 22:44:55 +00:00
formatter = logging.Formatter(
"%(asctime)s - %(levelname)s - %(message)s"
)
2025-11-30 18:28:44 +00:00
2025-11-30 22:44:55 +00:00
# ------------------------------
# 1) Handler de consola (siempre)
# ------------------------------
2025-11-30 18:28:44 +00:00
h_console = logging.StreamHandler(sys.stdout)
h_console.setFormatter(formatter)
logger.addHandler(h_console)
2025-11-30 22:44:55 +00:00
# ------------------------------
# 2) Handler de fichero (solo prod)
# ------------------------------
2025-12-01 08:55:54 +00:00
is_production = os.getenv("ENV") == "production"
2025-11-30 22:44:55 +00:00
2025-12-01 08:55:54 +00:00
if log_path and is_production:
2025-11-30 22:44:55 +00:00
p = Path(log_path)
# Aseguramos directorios
p.parent.mkdir(parents=True, exist_ok=True)
# Puedes usar FileHandler simple, pero Rotating es más seguro.
2025-11-30 18:28:44 +00:00
h_file = RotatingFileHandler(
2025-11-30 22:44:55 +00:00
filename=str(p),
maxBytes=max_bytes,
backupCount=backup_count,
encoding="utf-8",
2025-11-30 18:28:44 +00:00
)
h_file.setFormatter(formatter)
logger.addHandler(h_file)
2025-12-01 08:55:54 +00:00
# Verificación explícita
try:
test_msg = f"Log file active at: {p}"
h_file.acquire()
h_file.stream.write(f"{test_msg}\n")
h_file.flush()
h_file.release()
logger.info(test_msg)
except Exception as e:
logger.error(f"ERROR: cannot write to log file {p}: {e}")
raise
2025-11-30 18:28:44 +00:00
return logger
# logger "global" ya creado
logger = create_logger()