Jelajahi Sumber

refactor: improve error handling and logging across services and parsers

Manuel 9 bulan lalu
induk
melakukan
aad546df6d

+ 7 - 4
parsers/cache.py

@@ -6,6 +6,7 @@ import traceback
 from dotenv import load_dotenv
 
 from config import Config
+from loguru import logger
 
 # Load environment variables from .env file
 load_dotenv()
@@ -195,16 +196,18 @@ def fetch_squid_cache_stats():
         default_stats["error"] = f"Connection refused to {SQUID_HOST}:{SQUID_PORT}"
         default_stats["connection_status"] = "connection_refused"
         return default_stats
-    except socket.gaierror as e:
-        default_stats["error"] = f"DNS resolution error for {SQUID_HOST}: {str(e)}"
+    except socket.gaierror:
+        logger.exception("DNS resolution error when contacting Squid host")
+        default_stats["error"] = "DNS resolution error"
         default_stats["connection_status"] = "dns_error"
         return default_stats
     except UnicodeDecodeError:
         default_stats["error"] = "Error decoding response from Squid"
         default_stats["connection_status"] = "decode_error"
         return default_stats
-    except Exception as e:
-        default_stats["error"] = f"Unexpected error: {str(e)}"
+    except Exception:
+        logger.exception("Unexpected error fetching cache stats")
+        default_stats["error"] = "Unexpected error"
         default_stats["connection_status"] = "unknown_error"
         return default_stats
 

+ 3 - 1
parsers/squid_info.py

@@ -7,6 +7,7 @@ from datetime import datetime
 from dotenv import load_dotenv
 
 from config import Config
+from loguru import logger
 
 load_dotenv()
 
@@ -126,7 +127,8 @@ def fetch_squid_info_stats():
         parts = response_text.split("\r\n\r\n", 1)
         data = parts[1] if len(parts) > 1 else response_text
     except Exception as e:
-        default_stats["error"] = str(e)
+        logger.exception("Error fetching squid info stats")
+        default_stats["error"] = "Error obteniendo información de Squid"
         if isinstance(e, TimeoutError):
             default_stats["connection_status"] = "timeout"
         elif isinstance(e, ConnectionRefusedError):

+ 32 - 4
routes/admin_routes.py

@@ -311,7 +311,14 @@ def blacklist_import():
             flash("Archivo importado correctamente", "success")
         except Exception as e:
             logger.exception("Error importando archivo de blacklist")
-            flash(f"Error al procesar el archivo: {str(e)}", "error")
+            try:
+                show_details = bool(current_app.debug)
+            except RuntimeError:
+                show_details = False
+            if show_details:
+                flash(f"Error al procesar el archivo: {str(e)}", "error")
+            else:
+                flash("Error al procesar el archivo", "error")
             return redirect(url_for("admin.manage_blacklist"))
 
     # Handle URL import
@@ -330,7 +337,14 @@ def blacklist_import():
         flash("Blacklist actualizada exitosamente", "success")
     except Exception as e:
         logger.exception("Error guardando BLACKLIST_DOMAINS")
-        flash(f"Error al guardar blacklist: {str(e)}", "error")
+        try:
+            show_details = bool(current_app.debug)
+        except RuntimeError:
+            show_details = False
+        if show_details:
+            flash(f"Error al guardar blacklist: {str(e)}", "error")
+        else:
+            flash("Error al guardar blacklist", "error")
 
     return redirect(url_for("admin.manage_blacklist"))
 
@@ -356,7 +370,14 @@ def blacklist_save_custom():
         flash("Lista personalizada guardada en BLACKLIST_DOMAINS", "success")
     except Exception as e:
         logger.exception("Error guardando lista personalizada")
-        flash(f"Error al guardar la lista: {str(e)}", "error")
+        try:
+            show_details = bool(current_app.debug)
+        except RuntimeError:
+            show_details = False
+        if show_details:
+            flash(f"Error al guardar la lista: {str(e)}", "error")
+        else:
+            flash("Error al guardar la lista", "error")
 
     return redirect(url_for("admin.manage_blacklist"))
 
@@ -642,7 +663,14 @@ def split_config_view():
         )
     except Exception as e:
         logger.exception("Error al cargar la vista de división de configuración")
-        flash(f"Error al cargar la vista: {str(e)}", "error")
+        try:
+            show_details = bool(current_app.debug)
+        except RuntimeError:
+            show_details = False
+        if show_details:
+            flash(f"Error al cargar la vista: {str(e)}", "error")
+        else:
+            flash("Error al cargar la vista", "error")
         return redirect(url_for("admin.admin_dashboard"))
 
 

+ 3 - 3
services/acls_service.py

@@ -51,7 +51,7 @@ def add_acl(
         return True, f"ACL '{name}' agregada exitosamente"
     except Exception as e:
         logger.exception("Error agregando ACL")
-        return False, str(e)
+        return False, "Error interno al agregar ACL"
 
 
 def edit_acl(
@@ -119,7 +119,7 @@ def edit_acl(
         return False, "Línea de ACL no encontrada"
     except Exception as e:
         logger.exception("Error editando ACL")
-        return False, str(e)
+        return False, "Error interno al editar ACL"
 
 
 def delete_acl(acl_index: int, config_manager) -> tuple[bool, str]:
@@ -167,4 +167,4 @@ def delete_acl(acl_index: int, config_manager) -> tuple[bool, str]:
         return True, f"ACL '{acl_to_delete['name']}' eliminada exitosamente"
     except Exception as e:
         logger.exception("Error eliminando ACL")
-        return False, str(e)
+        return False, "Error interno al eliminar ACL"

+ 5 - 2
services/blacklist_users.py

@@ -6,6 +6,7 @@ from sqlalchemy.exc import SQLAlchemyError
 from sqlalchemy.orm import Session
 
 from database.database import get_dynamic_models, get_engine
+from loguru import logger
 
 
 def find_blacklisted_sites(
@@ -132,8 +133,10 @@ def find_blacklisted_sites(
                 total_results += table_count
 
     except SQLAlchemyError as e:
-        print(f"Database error: {e}")
-        return {"error": str(e)}
+
+
+        logger.exception("Database error while searching blacklisted sites")
+        return {"error": "Error interno del servidor"}
 
     return {
         "results": results,

+ 1 - 1
services/config_service.py

@@ -7,4 +7,4 @@ def save_config(new_content: str, config_manager) -> tuple[bool, str]:
         return True, "Configuration saved successfully"
     except Exception as e:
         logger.exception("Error saving configuration")
-        return False, str(e)
+        return False, "Error interno al guardar la configuración"

+ 2 - 6
services/db_admin_service.py

@@ -41,10 +41,6 @@ def delete_table_data(table_name: str):
             "message": f"Datos de la tabla '{table_name}' eliminados correctamente",
         }, 200
 
-    except Exception as e:
+    except Exception:
         logger.exception("Error deleting data from table %s", table_name)
-        return {
-            "status": "error",
-            "message": "Error interno del servidor",
-            "details": str(e),
-        }, 500
+        return {"status": "error", "message": "Error interno del servidor"}, 500

+ 3 - 3
services/delay_pools_service.py

@@ -42,7 +42,7 @@ def delete_delay_pool(pool_number: str, config_manager) -> tuple[bool, str]:
         return True, f"Delay Pool #{pool_number} eliminado exitosamente"
     except Exception as e:
         logger.exception("Error eliminando delay pool")
-        return False, str(e)
+        return False, "Error interno al eliminar delay pool"
 
 
 def edit_delay_pool(
@@ -121,7 +121,7 @@ def edit_delay_pool(
         return True, f"Delay Pool #{pool_number} actualizado exitosamente"
     except Exception as e:
         logger.exception("Error actualizando delay pool")
-        return False, str(e)
+        return False, "Error interno al actualizar delay pool"
 
 
 def add_delay_pool(
@@ -160,4 +160,4 @@ def add_delay_pool(
         return True, f"Delay Pool #{pool_number} creado exitosamente"
     except Exception as e:
         logger.exception("Error creando delay pool")
-        return False, str(e)
+        return False, "Error interno al crear delay pool"

+ 9 - 6
services/get_reports.py

@@ -5,6 +5,7 @@ from sqlalchemy import Column, Integer, String, desc, func, inspect
 from sqlalchemy.orm import Session, relationship
 
 from database.database import get_concat_function, get_dynamic_models
+from loguru import logger
 
 
 def get_important_metrics(db: Session, UserModel, LogModel):
@@ -131,9 +132,11 @@ def get_important_metrics(db: Session, UserModel, LogModel):
 
         return results
 
-    except Exception as e:
+    except Exception:
         # Log error but return empty structure
-        print(f"Error in get_important_metrics: {str(e)}")
+
+
+        logger.exception("Error in get_important_metrics")
         return {}
 
 
@@ -203,8 +206,8 @@ def get_metrics_by_date_range(start_date: str, end_date: str, db: Session):
             # ...
 
             current_dt += timedelta(days=1)
-        except Exception as e:
-            print(f"Error processing {date_suffix}: {str(e)}")
+        except Exception:
+            logger.exception(f"Error processing date {date_suffix}")
             current_dt += timedelta(days=1)
 
     return consolidated_results
@@ -215,8 +218,8 @@ def has_table(db: Session, table_name: str) -> bool:
         # Usar el inspector para verificar existencia de tabla
         inspector = inspect(db.get_bind())
         return inspector.has_table(table_name)
-    except Exception as e:
-        print(f"Error checking table {table_name}: {str(e)}")
+    except Exception:
+        logger.exception(f"Error checking table {table_name}")
         return False
 
 

+ 4 - 4
services/http_access_service.py

@@ -39,7 +39,7 @@ def delete_http_access(rule_index: int, config_manager) -> tuple[bool, str]:
         return True, "Regla HTTP Access eliminada exitosamente"
     except Exception as e:
         logger.exception("Error eliminando http_access")
-        return False, str(e)
+        return False, "Error interno al eliminar regla http_access"
 
 
 def edit_http_access(
@@ -93,7 +93,7 @@ def edit_http_access(
         return True, "Regla HTTP Access actualizada exitosamente"
     except Exception as e:
         logger.exception("Error actualizando http_access")
-        return False, str(e)
+        return False, "Error interno al actualizar regla http_access"
 
 
 def add_http_access(
@@ -129,7 +129,7 @@ def add_http_access(
         return True, "Regla HTTP Access agregada exitosamente"
     except Exception as e:
         logger.exception("Error agregando http_access")
-        return False, str(e)
+        return False, "Error interno al agregar regla http_access"
 
 
 def move_http_access(
@@ -170,4 +170,4 @@ def move_http_access(
         return True, "Regla movida exitosamente"
     except Exception as e:
         logger.exception("Error moviendo http_access")
-        return False, str(e)
+        return False, "Error interno al mover regla http_access"

+ 27 - 37
services/squid_config_splitter.py

@@ -216,14 +216,12 @@ class SquidConfigSplitter:
         try:
             shutil.copy2(self.input_file, backup_file)
             logger.info(f"Backup created: {backup_file}")
-        except PermissionError as e:
-            error_msg = f"Permission denied to create backup file: {backup_file}. Error: {str(e)}"
-            logger.error(error_msg)
-            raise RuntimeError(error_msg)
+        except PermissionError:
+            logger.exception("Permission denied to create backup file: %s", backup_file)
+            raise RuntimeError("Permission denied to create backup file")
         except Exception as e:
-            error_msg = f"Failed to create backup: {backup_file}. Error: {str(e)}"
-            logger.error(error_msg)
-            raise RuntimeError(error_msg)
+            logger.exception("Failed to create backup file: %s", backup_file)
+            raise RuntimeError("Failed to create backup file")
 
         # Create the output directory if it doesn't exist
         try:
@@ -267,18 +265,14 @@ class SquidConfigSplitter:
                     try:
                         target = self._classify_line(stripped)
                     except ValueError as e:
-                        error_msg = f"Error classifying line {lineno}: {stripped}\nError: {str(e)}"
-                        logger.error(error_msg)
-                        raise RuntimeError(error_msg)
+                        logger.exception("Error classifying line %s: %s", lineno, stripped)
+                        raise RuntimeError("Error classifying configuration line")
 
                     if target == self.unknown_file and self.strict:
-                        error_msg = (
-                            f"Unknown directive at line {lineno}: '{stripped}'\n"
-                            f"This directive is not recognized by the splitter rules. "
-                            f"Consider adding a rule for it or disable strict mode."
+                        logger.error("Unknown directive at line %s: %s", lineno, stripped)
+                        raise RuntimeError(
+                            "Unknown directive found in strict mode. Review configuration."
                         )
-                        logger.error(error_msg)
-                        raise RuntimeError(error_msg)
 
                     buffers.setdefault(target, [])
                     buffers[target].extend(pending_comments)
@@ -300,16 +294,12 @@ class SquidConfigSplitter:
                         f.writelines(content)
                     results[filename] = len(content)
                     logger.info(f"[OK] {path} ({len(content)} lines)")
-                except PermissionError as e:
-                    error_msg = (
-                        f"Permission denied writing to file: {path}. Error: {str(e)}"
-                    )
-                    logger.error(error_msg)
-                    raise RuntimeError(error_msg)
-                except Exception as e:
-                    error_msg = f"Failed to write file: {path}. Error: {str(e)}"
-                    logger.error(error_msg)
-                    raise RuntimeError(error_msg)
+                except PermissionError:
+                    logger.exception("Permission denied writing to file: %s", path)
+                    raise RuntimeError("Permission denied writing generated file")
+                except Exception:
+                    logger.exception("Failed to write file: %s", path)
+                    raise RuntimeError("Failed to write generated file")
 
             # Generate the new main squid.conf with includes
             self._generate_main_config(buffers)
@@ -320,19 +310,19 @@ class SquidConfigSplitter:
             if not validation_result["success"]:
                 error_details = validation_result.get("error_message", "Unknown error")
                 logger.error(
-                    f"Squid configuration validation failed. Rolling back changes. Error: {error_details}"
+                    "Squid configuration validation failed. Rolling back changes. Error: %s",
+                    error_details,
                 )
                 self._rollback_changes(backup_file, list(buffers.keys()))
                 raise RuntimeError(
-                    f"Squid configuration validation failed. Changes have been reverted.\n"
-                    f"Error details: {error_details}"
+                    "Squid configuration validation failed. Changes have been reverted."
                 )
 
             logger.info("Squid configuration validated successfully.")
             return results
 
-        except Exception as e:
-            logger.exception(f"Error splitting configuration file: {e}")
+        except Exception:
+            logger.exception("Error splitting configuration file")
             raise
 
     def _validate_squid_config(self) -> dict:
@@ -431,9 +421,9 @@ class SquidConfigSplitter:
 
             logger.info("Rollback completed successfully.")
 
-        except Exception as e:
-            logger.error(f"Error during rollback: {e}")
-            raise RuntimeError(f"Rollback failed: {e}")
+        except Exception:
+            logger.exception("Error during rollback")
+            raise RuntimeError("Rollback failed")
 
     def _generate_main_config(self, buffers: dict[str, list[str]]) -> None:
         header = [
@@ -459,9 +449,9 @@ class SquidConfigSplitter:
             logger.info(
                 f"Main configuration file regenerated with {len(includes)} includes in correct dependency order"
             )
-        except Exception as e:
-            logger.error(f"Failed to generate main config: {e}")
-            raise RuntimeError(f"Failed to generate main config: {e}")
+        except Exception:
+            logger.exception("Failed to generate main config")
+            raise RuntimeError("Failed to generate main config")
 
     def _ensure_auth_file(self, buffers: dict[str, list[str]]) -> None:
         """

+ 16 - 8
services/system_info.py

@@ -6,6 +6,7 @@ import subprocess
 import time
 
 import psutil
+from loguru import logger
 
 # Variables globales para el cálculo de estadísticas de red
 _last_net_io = None
@@ -30,7 +31,8 @@ def get_network_info():
                         }
                     )
     except Exception as e:
-        return f"Error: {str(e)}"
+        logger.exception("Error getting network interfaces")
+        return []
 
     return ips if ips else "Not available"
 
@@ -62,7 +64,8 @@ def get_uptime():
         minutes = int((uptime_seconds % 3600) // 60)
         return f"{days}d {hours}h {minutes}m"
     except Exception as e:
-        return f"Error getting uptime: {str(e)}"
+        logger.exception("Error getting uptime")
+        return "Unknown"
 
 
 def get_ram_info():
@@ -75,7 +78,8 @@ def get_ram_info():
             "percent": f"{ram.percent}%",
         }
     except Exception as e:
-        return f"Error: {str(e)}"
+        logger.exception("Error getting RAM info")
+        return {}
 
 
 def get_swap_info():
@@ -90,7 +94,8 @@ def get_swap_info():
             }
         return "Not available"
     except Exception as e:
-        return f"Error: {str(e)}"
+        logger.exception("Error getting swap info")
+        return "Not available"
 
 
 def get_cpu_info():
@@ -103,7 +108,7 @@ def get_cpu_info():
             freq_max = cpu_freq.max
         except Exception as e:
             freq_current = freq_min = freq_max = "N/A"
-            print(f"Error getting CPU frequency info: {str(e)}")
+            logger.exception("Error getting CPU frequency info")
 
         cpu_times = psutil.cpu_times_percent(interval=0.5, percpu=False)
         return {
@@ -124,7 +129,8 @@ def get_cpu_info():
             "idle_time": f"{cpu_times.idle}%",
         }
     except Exception as e:
-        return f"Error: {str(e)}"
+        logger.exception("Error getting CPU info")
+        return {}
 
 
 def get_network_stats():
@@ -173,6 +179,7 @@ def get_network_stats():
             "packets_recv": current_net_io.packets_recv,
         }
     except Exception as e:
+        logger.exception("Error getting network stats")
         return {
             "up_mbps": 0.0,
             "down_mbps": 0.0,
@@ -182,7 +189,7 @@ def get_network_stats():
             "bytes_recv_total": 0,
             "packets_sent": 0,
             "packets_recv": 0,
-            "error": str(e),
+            "error": "Internal error",
         }
 
 
@@ -200,7 +207,8 @@ def get_timezone():
             return f"{match.group(1)} {match.group(2)}"
         return "Unknown"
     except Exception as e:
-        return f"Error getting timezone: {str(e)}"
+        logger.exception("Error getting timezone")
+        return "Unknown"
 
 
 def get_system_type():

+ 3 - 2
services/telegram_integration.py

@@ -339,12 +339,13 @@ async def telegram_health_check() -> dict[str, Any]:
         health = await _telegram_service.health_check()
         return health
     except Exception as e:
-        logger.error(f"Telegram health check failed: {e}")
+        logger.exception("Telegram health check failed")
+        err = str(e) if getattr(Config, "DEBUG", False) else "Internal error"
         return {
             "enabled": Config.TELEGRAM_ENABLED,
             "initialized": True,
             "connected": False,
-            "error": str(e),
+            "error": err,
         }
 
 

+ 2 - 2
services/telegram_service.py

@@ -420,8 +420,8 @@ class TelegramService:
                 status["user_id"] = me.id
                 status["username"] = getattr(me, "username", None)
         except Exception as e:
-            status["error"] = str(e)
-            logger.error(f"Health check failed: {e}")
+            logger.exception("Health check failed")
+            status["error"] = "Health check failed"
 
         return status
 

+ 3 - 3
services/user_service.py

@@ -24,7 +24,7 @@ def create_user(username: str, password: str, role: str = "admin") -> tuple[bool
         return False, "Error al crear usuario. El nombre de usuario puede existir."
     except Exception as e:
         logger.exception("Error creating user")
-        return False, str(e)
+        return False, "Error interno al crear usuario"
 
 
 def update_user(
@@ -44,7 +44,7 @@ def update_user(
         return False, "Error al actualizar usuario"
     except Exception as e:
         logger.exception("Error updating user")
-        return False, str(e)
+        return False, "Error interno al actualizar usuario"
 
 
 def delete_user(user_id: int) -> tuple[bool, str]:
@@ -58,4 +58,4 @@ def delete_user(user_id: int) -> tuple[bool, str]:
         )
     except Exception as e:
         logger.exception("Error deleting user")
-        return False, str(e)
+        return False, "Error interno al eliminar usuario"

+ 33 - 18
utils/updateSquid.py

@@ -3,7 +3,7 @@ import os
 import platform
 import subprocess
 import tempfile
-
+from loguru import logger
 from dotenv import load_dotenv
 
 load_dotenv()
@@ -15,15 +15,23 @@ def update_squid():
         squid_instalado = pre_check.returncode == 0
     except FileNotFoundError:
         squid_instalado = False
-        print(
-            "El binario de Squid no se encontró en el sistema (aún no instalado)",
-            "info",
-        )
+        try:
+
+            logger.info("El binario de Squid no se encontró en el sistema (aún no instalado)")
+        except Exception:
+            pass
 
     if squid_instalado:
-        print("Squid ya está instalado:", pre_check.stdout.strip(), "info")
+        try:
+
+            logger.info(f"Squid ya está instalado: {pre_check.stdout.strip()}")
+        except Exception:
+            pass
     else:
-        print("Squid no está instalado o no se detectó instalación previa", "info")
+        try:
+            logger.info("Squid no está instalado o no se detectó instalación previa")
+        except Exception:
+            pass
     try:
         os_info = platform.freedesktop_os_release()
         os_id = os_info.get("ID", "").lower()
@@ -48,13 +56,14 @@ def update_squid():
             env=env,
         )
         if version_info.returncode != 0:
-            print("Error obteniendo información de versión", "error")
+            logger.error("Error obteniendo información de versión")
             return False
 
         try:
             latest_version = json.loads(version_info.stdout)["tag_name"]
         except (json.JSONDecodeError, KeyError):
-            print("Error procesando versión", "error")
+
+            logger.error("Error procesando versión")
             return False
 
         package_name = f"squid_{latest_version}-{os_id}-{codename}_amd64.deb"
@@ -64,10 +73,8 @@ def update_squid():
             ["wget", "--spider", download_url], capture_output=True, text=True, env=env
         )
         if check_package.returncode != 0:
-            print(
-                f"Paquete no disponible para {os_id.capitalize()} {codename.capitalize()}",
-                "error",
-            )
+
+            logger.error(f"Paquete no disponible para {os_id.capitalize()} {codename.capitalize()}")
             return False
 
         with tempfile.NamedTemporaryFile(
@@ -81,7 +88,8 @@ def update_squid():
                 env=env,
             )
         if download.returncode != 0:
-            print("Error descargando el paquete", "error")
+            
+            logger.error("Error descargando el paquete")
             return False
 
         apt_env = env.copy()
@@ -95,7 +103,8 @@ def update_squid():
 
         install = subprocess.run(["dpkg", "-i", "--force-overwrite", package_path])
         if install.returncode != 0:
-            print("Error instalando el paquete", "error")
+
+            logger.error("Error instalando el paquete")
             subprocess.run(["apt", "install", "-f", "-y"], env=apt_env)
 
         subprocess.run(["cp", f"{os.getcwd()}/./utils/squid", "/etc/init.d/"])
@@ -106,11 +115,17 @@ def update_squid():
         squid_check = subprocess.run(["squid", "-v"], capture_output=True, text=True)
 
         if squid_check.returncode != 0:
-            print("Error en instalación final", "error")
+
+            logger.error("Error en instalación final")
             return False
 
-        print(f"Actualización a {latest_version} completada exitosamente", "success")
+        try:
+
+            logger.info(f"Actualización a {latest_version} completada exitosamente")
+        except Exception:
+            pass
         return True
     except Exception as e:
-        print(f"Error crítico: {str(e)}", "error")
+
+        logger.exception("Error crítico durante la actualización de Squid")
         return False

+ 7 - 4
utils/updateSquidStats.py

@@ -4,6 +4,7 @@ import tempfile
 
 import requests
 from dotenv import load_dotenv
+from loguru import logger
 
 load_dotenv()
 
@@ -35,12 +36,14 @@ def updateSquidStats():
             subprocess.run(["bash", tmp_script_path, "--update"], env=env)
             os.unlink(tmp_script_path)
             return True
-        except Exception as e:
-            print(f"Error descargando el script de actualizacion: {str(e)}", "error")
+        except Exception:
+
+            logger.exception("Error descargando el script de actualización")
             if "tmp_script_path" in locals() and os.path.exists(tmp_script_path):
                 os.unlink(tmp_script_path)
             return False
 
-    except Exception as e:
-        print(f"Error crítico: {str(e)}", "error")
+    except Exception:
+
+        logger.exception("Error crítico en updateSquidStats")
         return False