70 lines
2.2 KiB
Python
70 lines
2.2 KiB
Python
import sys
|
|||
|
|
import os
|
||
|
|
from datetime import datetime, timedelta
|
||
|
|
|
||
|
|
########################################################
|
||
|
|
class MultiStream:
|
||
|
|
"""
|
||
|
|
Clase para redirigir la salida a múltiples flujos (consola y archivo).
|
||
|
|
"""
|
||
|
|
def __init__(self, *streams):
|
||
|
|
self.streams = streams
|
||
|
|
|
||
|
|
def write(self, data):
|
||
|
|
for stream in self.streams:
|
||
|
|
stream.write(data)
|
||
|
|
stream.flush()
|
||
|
|
|
||
|
|
def flush(self):
|
||
|
|
for stream in self.streams:
|
||
|
|
stream.flush()
|
||
|
|
|
||
|
|
########################################################
|
||
|
|
def setup_logger():
|
||
|
|
"""
|
||
|
|
Configura la redirección de stdout y stderr a un archivo de log y a la consola.
|
||
|
|
Retorna la ruta del archivo de log creado.
|
||
|
|
"""
|
||
|
|
log_dir = "logs"
|
||
|
|
if not os.path.exists(log_dir):
|
||
|
|
os.makedirs(log_dir)
|
||
|
|
|
||
|
|
# Nombre del archivo: YYYY-MM-DD_HH-MM-SS.log
|
||
|
|
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
||
|
|
log_filename = f"{timestamp}.log"
|
||
|
|
log_path = os.path.join(log_dir, log_filename)
|
||
|
|
|
||
|
|
# Abrir archivo en modo append con encoding utf-8 para soportar iconos
|
||
|
|
log_file = open(log_path, "a", encoding="utf-8")
|
||
|
|
|
||
|
|
# Redirigir stdout y stderr
|
||
|
|
sys.stdout = MultiStream(sys.stdout, log_file)
|
||
|
|
sys.stderr = MultiStream(sys.stderr, log_file)
|
||
|
|
|
||
|
|
return log_path
|
||
|
|
|
||
|
|
########################################################
|
||
|
|
def limpiar_logs_antiguos(dias=7):
|
||
|
|
"""
|
||
|
|
Elimina archivos de log con más de 'n' días de antigüedad.
|
||
|
|
"""
|
||
|
|
log_dir = "logs"
|
||
|
|
if not os.path.exists(log_dir):
|
||
|
|
return
|
||
|
|
|
||
|
|
limite = datetime.now() - timedelta(days=dias)
|
||
|
|
count = 0
|
||
|
|
|
||
|
|
for archivo in os.listdir(log_dir):
|
||
|
|
ruta_archivo = os.path.join(log_dir, archivo)
|
||
|
|
if os.path.isfile(ruta_archivo) and archivo.endswith(".log"):
|
||
|
|
fecha_archivo = datetime.fromtimestamp(os.path.getmtime(ruta_archivo))
|
||
|
|
if fecha_archivo < limite:
|
||
|
|
try:
|
||
|
|
os.remove(ruta_archivo)
|
||
|
|
count += 1
|
||
|
|
except Exception as e:
|
||
|
|
print(f"⚠️ Error al eliminar log {archivo}: {e}")
|
||
|
|
|
||
|
|
if count > 0:
|
||
|
|
print(f"🧹 Se eliminaron {count} archivos de log antiguos (más de {dias} días).")
|