Improve log output for installer

select_mono_multi
Nicolas Arenas 2025-05-07 17:43:59 +02:00
parent 6217bc71eb
commit 3f9265cf69
1 changed files with 26 additions and 20 deletions

View File

@ -10,15 +10,18 @@ import sys # Importar sys para leer los argumentos del script
import logging # Importar el módulo logging import logging # Importar el módulo logging
CONFIGS_DIR = "/tmp/oginstall" CONFIGS_DIR = "/tmp/oginstall"
os.makedirs(CONFIGS_DIR, exist_ok=True) LOGS_DIR = "/var/log/oginstaller"
REPO_URL = "https://ognproject.evlt.uma.es/gitea/opengnsys/ogcore.git" REPO_URL = "https://ognproject.evlt.uma.es/gitea/opengnsys/ogcore.git"
# Configurar logging # Configurar logging y directorio configuración
try: try:
if not os.path.exists(LOGS_DIR):
os.makedirs(LOGS_DIR, exist_ok=True)
LOG_FILE = os.path.join(LOGS_DIR, "oginstall.log")
if not os.path.exists(CONFIGS_DIR): if not os.path.exists(CONFIGS_DIR):
os.makedirs(CONFIGS_DIR, exist_ok=True) # Crear el directorio si no existe os.makedirs(CONFIGS_DIR, exist_ok=True)
LOG_FILE = os.path.join(CONFIGS_DIR, "debug.log")
logging.basicConfig( logging.basicConfig(
filename=LOG_FILE, filename=LOG_FILE,
level=logging.DEBUG, level=logging.DEBUG,
@ -27,7 +30,7 @@ try:
logging.debug("Inicio del programa") # Mensaje inicial para verificar que el log se crea logging.debug("Inicio del programa") # Mensaje inicial para verificar que el log se crea
except Exception as e: except Exception as e:
print(f"[ERROR] No se pudo configurar el logging: {e}") print(f"[ERROR] No se pudo configurar el logging: {e}")
print(f"[ERROR] Verifica los permisos del directorio: {CONFIGS_DIR}") print(f"[ERROR] Verifica los permisos del directorio: {LOGS_DIR}")
exit(1) # Salir si no se puede configurar el logging exit(1) # Salir si no se puede configurar el logging
def get_network_interfaces(): def get_network_interfaces():
@ -399,20 +402,16 @@ class InstallationProgressForm(npyscreen.FormBaseNew):
self.progress_box.values.append(message) self.progress_box.values.append(message)
self.progress_box.display() self.progress_box.display()
def update_log(self, log_lines): def update_log(self, new_line):
"""Actualiza el log en tiempo real en la parte inferior.""" """Actualiza el log en tiempo real en la parte inferior."""
# Limpiar caracteres especiales de las líneas del log max_lines = 10 # Número máximo de líneas a mostrar
cleaned_lines = [self._clean_text(line) for line in log_lines] self.log_box.values.append(new_line.strip()) # Agregar la nueva línea
self.log_box.values = cleaned_lines[-self.log_box.height:] # Mostrar solo las últimas líneas self.log_box.values = self.log_box.values[-max_lines:] # Mantener solo las últimas `max_lines` líneas
self.log_box.display() self.log_box.display()
def _clean_text(self, text):
"""Elimina caracteres especiales o no imprimibles del texto."""
return ''.join(c if c.isprintable() else '?' for c in text)
def install_components_with_ui(form, components, selected_tag): def install_components_with_ui(form, components, selected_tag):
"""Instala los componentes seleccionados mostrando el progreso y el log en tiempo real.""" """Instala los componentes seleccionados mostrando el progreso y el log en tiempo real."""
log_file_path = os.path.join(CONFIGS_DIR, "installation.log") log_file_path = os.path.join(LOGS_DIR, "installation.log")
installed_packages = [] # Lista de paquetes instalados correctamente installed_packages = [] # Lista de paquetes instalados correctamente
failed_packages = [] # Lista de paquetes que fallaron failed_packages = [] # Lista de paquetes que fallaron
@ -420,7 +419,8 @@ def install_components_with_ui(form, components, selected_tag):
start_time = time.time() start_time = time.time()
try: try:
with open(log_file_path, "w") as log_file: # Abrir el archivo de log en modo sin buffer
with open(log_file_path, "w", buffering=1) as log_file: # Line-buffered mode
total_packages = len(components) total_packages = len(components)
# Hilo para leer el log en tiempo real # Hilo para leer el log en tiempo real
@ -428,10 +428,10 @@ def install_components_with_ui(form, components, selected_tag):
with open(log_file_path, "r") as log_reader: with open(log_file_path, "r") as log_reader:
log_reader.seek(0, os.SEEK_END) # Ir al final del archivo log_reader.seek(0, os.SEEK_END) # Ir al final del archivo
while True: while True:
line = log_reader.readline() line = log_reader.readline() # Leer una nueva línea
if line: if line:
form.update_log([line]) # Actualizar el log línea por línea form.update_log(line) # Actualizar el log en la interfaz
time.sleep(0.1) #time.sleep(0.1) # Pequeña pausa para evitar uso excesivo de CPU
log_thread = threading.Thread(target=tail_log, daemon=True) log_thread = threading.Thread(target=tail_log, daemon=True)
log_thread.start() log_thread.start()
@ -443,12 +443,15 @@ def install_components_with_ui(form, components, selected_tag):
# Crear una barra de progreso para el paquete # Crear una barra de progreso para el paquete
install_command = f"DEBIAN_FRONTEND=noninteractive apt-get install -y {package}" install_command = f"DEBIAN_FRONTEND=noninteractive apt-get install -y {package}"
process = subprocess.Popen( process = subprocess.Popen(
install_command, shell=True, text=True, stdout=log_file, stderr=log_file install_command, shell=True, text=True, stdout=log_file, stderr=log_file, bufsize=1 # Line-buffered
) )
# Esperar a que el proceso de instalación termine # Esperar a que el proceso de instalación termine
process.wait() process.wait()
# Forzar el vaciado del buffer del archivo de log
log_file.flush()
# Registrar errores en el archivo de registro # Registrar errores en el archivo de registro
if process.returncode != 0: if process.returncode != 0:
error_message = f"Error al instalar el paquete {package}. Consulta el archivo de registro: {log_file_path}" error_message = f"Error al instalar el paquete {package}. Consulta el archivo de registro: {log_file_path}"
@ -463,10 +466,13 @@ def install_components_with_ui(form, components, selected_tag):
form.update_progress("Instalando paquete adicional: ogclient") form.update_progress("Instalando paquete adicional: ogclient")
install_command = "DEBIAN_FRONTEND=noninteractive apt-get install -y ogclient" install_command = "DEBIAN_FRONTEND=noninteractive apt-get install -y ogclient"
process = subprocess.Popen( process = subprocess.Popen(
install_command, shell=True, text=True, stdout=log_file, stderr=log_file install_command, shell=True, text=True, stdout=log_file, stderr=log_file, bufsize=1 # Line-buffered
) )
process.wait() process.wait()
# Forzar el vaciado del buffer del archivo de log
log_file.flush()
if process.returncode != 0: if process.returncode != 0:
error_message = f"Error al instalar el paquete ogclient. Consulta el archivo de registro: {log_file_path}" error_message = f"Error al instalar el paquete ogclient. Consulta el archivo de registro: {log_file_path}"
form.update_progress(error_message) form.update_progress(error_message)