primer commit
This commit is contained in:
commit
2be35d7e55
17 files changed
+2709
No files matched your search
@@ -0,0 +1,93 @@
|
||||
import sys
|
||||
import os
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
_stdout_original = sys.stdout
|
||||
_stderr_original = sys.stderr
|
||||
_file_stream = None
|
||||
_log_dir = "logs"
|
||||
|
||||
# ============================================================================
|
||||
class MultiStream:
|
||||
def __init__(self, *streams):
|
||||
self.streams = list(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 reemplazar_file(self, old_fh, new_fh):
|
||||
for i, s in enumerate(self.streams):
|
||||
if s is old_fh:
|
||||
self.streams[i] = new_fh
|
||||
return
|
||||
|
||||
# ============================================================================
|
||||
def _ruta_log(hoy=None):
|
||||
if hoy is None:
|
||||
hoy = datetime.now().strftime("%Y-%m-%d")
|
||||
if not os.path.exists(_log_dir):
|
||||
os.makedirs(_log_dir)
|
||||
return os.path.join(_log_dir, f"{hoy}.log")
|
||||
|
||||
# ============================================================================
|
||||
def setup_logger():
|
||||
global _file_stream
|
||||
log_path = _ruta_log()
|
||||
_file_stream = open(log_path, "a", encoding="utf-8")
|
||||
sys.stdout = MultiStream(_stdout_original, _file_stream)
|
||||
sys.stderr = MultiStream(_stderr_original, _file_stream)
|
||||
return log_path
|
||||
|
||||
# ============================================================================
|
||||
def rotar_log():
|
||||
global _file_stream
|
||||
hoy = datetime.now().strftime("%Y-%m-%d")
|
||||
log_path = _ruta_log(hoy)
|
||||
|
||||
if _file_stream and os.path.abspath(_file_stream.name) == os.path.abspath(log_path):
|
||||
return
|
||||
|
||||
nuevo_fh = open(log_path, "a", encoding="utf-8")
|
||||
if isinstance(sys.stdout, MultiStream):
|
||||
sys.stdout.reemplazar_file(_file_stream, nuevo_fh)
|
||||
if isinstance(sys.stderr, MultiStream):
|
||||
sys.stderr.reemplazar_file(_file_stream, nuevo_fh)
|
||||
try:
|
||||
_file_stream.close()
|
||||
except Exception:
|
||||
pass
|
||||
_file_stream = nuevo_fh
|
||||
print(f"📄 Log rotado a: {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).")
|
||||
# ============================================================================
|
||||
Reference in new issue
Block a user