diff --git a/.env b/.env index 15d02eb..d9bdfe1 100644 --- a/.env +++ b/.env @@ -3,7 +3,6 @@ DB_HOST=162.19.78.131 DB_USER=sondes DB_PASSWORD=TX.)-U1!zq5Axdk4 DB_NAME=Sondes -VPS_PASSWORD=lpZwixbBUFtGY # MQTT MQTT_HOST=162.19.78.131 @@ -11,7 +10,6 @@ MQTT_PORT=1883 MQTT_USER=sondes MQTT_PASS=3J@bjYP0 - # paramètres mail SMTP_HOST=smtp.mail.ovh.net SMTP_PORT=465 diff --git a/app/visualiseur_logs.py b/app/visualiseur_logs.py index bbea9eb..29f0b46 100644 --- a/app/visualiseur_logs.py +++ b/app/visualiseur_logs.py @@ -1,164 +1,116 @@ # visualiseur_logs.py -import os +# Dépendances: streamlit, paramiko +# pip install streamlit paramiko + +import html +import time from datetime import datetime import streamlit as st -# Dépendances SSH & .env try: import paramiko except ImportError: paramiko = None -try: - from dotenv import load_dotenv -except ImportError: - load_dotenv = None + +# ========================= +# CONFIG — À RENSEIGNER +# ========================= +VPS_HOST = "162.19.78.131" # ← mets ton IP/DNS +VPS_PORT = 22 # ← port SSH +VPS_USER = "debian" # ← utilisateur +VPS_PASSWORD = "lpZwixbBUFtGY" # ← mot de passe +VPS_LOG_DIR = "/home/debian/Gestion_sondes/Logs" # ← dossier des logs sur le VPS # ========================= -# CONFIG & CHARGEMENT .ENV +# UI # ========================= st.set_page_config(page_title="Visualiseur de Logs (VPS, password)", layout="wide") st.title("🧾 Visualiseur de fichiers logs (VPS)") +st.caption(f"Cible : {VPS_USER}@{VPS_HOST}:{VPS_PORT} • Dossier logs : {VPS_LOG_DIR}") -# Chemins possibles du .env -CANDIDATE_ENV = [ - "/home/debian/Gestion_sondes/.env", - os.path.join(os.path.expanduser("~"), "Gestion_sondes", ".env"), - ".env", -] -ENV_LOADED_FROM = None -if load_dotenv: - for p in CANDIDATE_ENV: - if os.path.isfile(p): - load_dotenv(p) - ENV_LOADED_FROM = p - break +if paramiko is None: + st.error("Paramiko n’est pas installé. Exécute : pip install paramiko") + st.stop() -# Valeurs par défaut (surchageables par .env) -VPS_HOST = os.getenv("VPS_HOST", "app.domo91.fr") -VPS_PORT = int(os.getenv("VPS_PORT", "22") or "22") -VPS_USER = os.getenv("VPS_USER", "debian") -VPS_PASSWORD = os.getenv("VPS_PASSWORD", "") -VPS_LOG_DIR = os.getenv("VPS_LOG_DIR", "/home/debian/Gestion_sondes/Logs") - - -# ========================= -# BARRE LATÉRALE -# ========================= +# Barre latérale : options d’affichage & refresh with st.sidebar: - st.header("⚙️ Configuration") - if not load_dotenv: - st.caption("Astuce : installe python-dotenv pour charger automatiquement un .env") - st.code("pip install python-dotenv", language="bash") - st.caption(f".env chargé depuis : `{ENV_LOADED_FROM or 'non trouvé'}`") - - VPS_HOST = st.text_input("Hôte VPS", value=VPS_HOST) - VPS_PORT = st.number_input("Port", value=VPS_PORT, min_value=1, max_value=65535, step=1) - VPS_USER = st.text_input("Utilisateur", value=VPS_USER) - VPS_LOG_DIR = st.text_input("Dossier des logs (VPS)", value=VPS_LOG_DIR) - VPS_PASSWORD = st.text_input("Mot de passe (VPS)", value=VPS_PASSWORD, type="password") - - st.markdown("---") - st.caption("Connexion par **mot de passe** uniquement (pas de clé).") + st.header("⚙️ Options") + auto_refresh = st.toggle("🔄 Rafraîchissement auto", value=False, key="auto_refresh") + refresh_interval = st.slider("Intervalle (secondes)", 2, 60, 5, key="refresh_interval") + if st.button("Rafraîchir maintenant"): + st.rerun() # ========================= -# FONCTIONS SSH (password) +# FONCTIONS SSH # ========================= def ssh_connect_password(host, port, user, password): """Retourne un client SSH connecté (password).""" - if paramiko is None: - raise RuntimeError("Paramiko n’est pas installé. Fais : pip install paramiko") - ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=host, port=int(port), username=user, password=password, timeout=10) return ssh - def list_logs_over_ssh(ssh, log_dir): """ - Retourne une liste triée (par mtime desc) de dicts : - [{'name': 'f.log', 'mtime': 1726140001.0, 'size': 12345}, ...] - Utilise 'find' + 'printf' pour robustesse et performance. + Liste les *.log du dossier (sans sous-dossiers), triés par mtime desc. + Retourne [{'name': 'f.log', 'mtime': 1234567890.0, 'size': 1024}, ...] """ - # -maxdepth 1 : uniquement dans le dossier - # -type f -name "*.log" : fichiers .log - # -printf "%T@ %s %f\n" : mtime_epoch size filename - cmd = f"bash -lc \"find '{log_dir}' -maxdepth 1 -type f -name '*.log' -printf '%T@ %s %f\\n' 2>/dev/null | sort -nr\"" + cmd = ( + f"bash -lc \"find '{log_dir}' -maxdepth 1 -type f -name '*.log' " + f"-printf '%T@ %s %f\\n' 2>/dev/null | sort -nr\"" + ) _, stdout, stderr = ssh.exec_command(cmd) - err = stderr.read().decode(errors="ignore").strip() + _ = stderr.read().decode(errors="ignore") # on ignore les warnings find out = stdout.read().decode(errors="ignore") - # Pas bloquant si 'find' écrit sur stderr pour des warnings, on ignore - logs = [] + items = [] for line in out.splitlines(): - line = line.strip() - if not line: - continue - parts = line.split(" ", 2) + parts = line.strip().split(" ", 2) if len(parts) < 3: continue try: - mtime = float(parts[0]) - size = int(parts[1]) - name = parts[2] - logs.append({"name": name, "mtime": mtime, "size": size}) + mtime = float(parts[0]); size = int(parts[1]); name = parts[2] + items.append({"name": name, "mtime": mtime, "size": size}) except Exception: continue - return logs - + return items def read_tail_over_ssh(ssh, remote_path, n_lines): - """ - Lit les N dernières lignes via 'tail -n' (rapide pour gros logs). - Retourne str (contenu brut). - """ + """Lit les N dernières lignes via 'tail -n' (rapide sur gros logs).""" n = max(1, int(n_lines)) cmd = f"bash -lc \"tail -n {n} '{remote_path}'\"" _, stdout, stderr = ssh.exec_command(cmd) err = stderr.read().decode(errors="ignore") - if err and "No such file" in err: + if "No such file" in err: raise FileNotFoundError(err) return stdout.read().decode(errors="ignore") - def backup_and_truncate_remote(ssh, remote_path): - """ - Crée une sauvegarde horodatée .bak et tronque le fichier à 0 octet. - Retourne le chemin de la sauvegarde. - """ + """Crée une sauvegarde horodatée .bak et tronque le fichier à 0 octet. Retourne le chemin .bak.""" ts = datetime.now().strftime("%Y%m%d-%H%M%S") bak = f"{remote_path}.{ts}.bak" - # cp (backup) + truncate (ou redirection fallback) cmd = ( f"bash -lc \"cp '{remote_path}' '{bak}' 2>/dev/null || true; " f"truncate -s 0 '{remote_path}' 2>/dev/null || : > '{remote_path}'\"" ) - _, stdout, stderr = ssh.exec_command(cmd) - _ = stdout.read() - err = stderr.read().decode(errors="ignore").strip() - # On tolère la plupart des messages ; on remonte seulement si 'No such file' - if "No such file" in err: - raise FileNotFoundError(err) + _, out, err = ssh.exec_command(cmd) + _ = out.read() + e = err.read().decode(errors="ignore").strip() + if "No such file" in e: + raise FileNotFoundError(e) return bak # ========================= -# CONTRÔLE DES CHAMPS AVANT CONNEXION +# CONNEXION & LISTE # ========================= -if not VPS_HOST or not VPS_USER or not VPS_LOG_DIR: - st.error("Renseigne au minimum Hôte, Utilisateur et Dossier des logs.") - st.stop() -if not VPS_PASSWORD: - st.error("Renseigne le mot de passe pour l’authentification.") +if not all([VPS_HOST, VPS_USER, VPS_PASSWORD, VPS_LOG_DIR]): + st.error("Complète les constantes en haut du fichier (hôte/utilisateur/mot de passe/dossier logs).") st.stop() - -# ========================= -# CONNEXION & LISTE DES LOGS -# ========================= try: ssh = ssh_connect_password(VPS_HOST, VPS_PORT, VPS_USER, VPS_PASSWORD) except Exception as e: @@ -177,37 +129,35 @@ if not logs: st.warning("Aucun fichier *.log trouvé dans ce dossier sur le VPS.") st.stop() -# Combobox des fichiers, triés par mtime desc -fichiers = [item["name"] for item in logs] -choix = st.selectbox("📂 Sélectionnez un fichier log (VPS) :", fichiers, index=0) +fichiers = [x["name"] for x in logs] +choix = st.selectbox("📂 Sélectionnez un fichier log :", fichiers, index=0) log_info = next((x for x in logs if x["name"] == choix), logs[0]) log_path = f"{VPS_LOG_DIR.rstrip('/')}/{choix}" -# Infos de bandeau mtime_dt = datetime.fromtimestamp(log_info["mtime"]) -st.caption( - f"VPS {VPS_USER}@{VPS_HOST} • `{choix}` — " - f"Taille : {log_info['size']:,} octets — Modifié le : {mtime_dt:%Y-%m-%d %H:%M:%S}" -) +st.caption(f"`{choix}` — Taille : {log_info['size']:,} o — Modifié : {mtime_dt:%Y-%m-%d %H:%M:%S}") # ========================= -# OPTIONS D'AFFICHAGE +# OPTIONS & LECTURE # ========================= -col1, col2 = st.columns([1, 1]) +col1, col2, col3 = st.columns([1, 1, 1.2]) with col1: filtre_erreurs = st.checkbox( "🔍 Afficher uniquement les erreurs", value=False, - help="Filtre sur ERROR, ❌, Traceback, failed, exception" + help="Filtre sur ERROR, ❌, Traceback, failed, exception, critical, fatal" ) with col2: - nb_lignes = st.slider("📏 Nombre de lignes à afficher", 10, 5000, 300) + nb_lignes = st.slider("📏 Lignes à afficher", 10, 5000, 300) +with col3: + highlight = st.checkbox( + "🖍️ Surligner erreurs/avertissements", + value=True, + help="Met en évidence ERROR/CRITICAL/EXCEPTION (rouge) et WARN (jaune)" + ) -# ========================= -# LECTURE DU CONTENU (tail) -# ========================= +# Lecture (on prend une marge quand filtre actif) try: - # Lis légèrement plus que demandé quand on filtre, pour avoir assez de matière marge = 300 if filtre_erreurs else 0 content = read_tail_over_ssh(ssh, log_path, nb_lignes + marge) lignes = content.splitlines(keepends=True) @@ -216,31 +166,50 @@ except Exception as e: st.error(f"Impossible de lire le fichier : {e}") st.stop() -# On peut fermer ici (les actions rouvriront une connexion fraîche) +# On peut fermer maintenant (les actions rouvriront une session propre) ssh.close() -# Filtre "erreurs" +# Filtrage if filtre_erreurs: - mots_cles = ["error", "❌", "traceback", "failed", "exception"] - lignes = [l for l in lignes if any(m in l.lower() for m in mots_cles)] + err_keys = ["error", "traceback", "failed", "exception", "critical", "fatal"] + lignes = [l for l in lignes if any(k in l.lower() for k in err_keys)] -# Affichage dernieres = lignes[-nb_lignes:] -st.text_area("📄 Contenu du fichier log :", "".join(dernieres), height=600) + +# Surlignage +def colorize(lines): + out = [] + for l in lines: + low = l.lower() + style = ( + "font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace;" + "white-space: pre-wrap; margin: 0; padding: 2px 6px; border-radius: 4px;" + ) + bg = None + if any(k in low for k in ["error", "traceback", "failed", "exception", "critical", "fatal", "❌"]): + bg = "#ffe6e6" # rouge clair + elif "warn" in low: + bg = "#fff8e1" # jaune clair + if bg: + style += f"background:{bg};" + out.append(f"