加入日志

This commit is contained in:
liuwei
2025-05-27 09:14:06 +08:00
parent 2054b3979c
commit eccf89095a

View File

@@ -3,6 +3,7 @@ import threading
import subprocess
import requests
from loguru import logger
class GlancesMonitor:
def __init__(self, email_sender, host='localhost', port=61208,
@@ -42,7 +43,8 @@ class GlancesMonitor:
response = requests.get(f"{self.api_url}/cpu")
response.raise_for_status()
return response.json().get('count', 1)
except Exception:
except Exception as e:
logger.error(e)
return 1
def start_glances(self):
@@ -57,12 +59,12 @@ class GlancesMonitor:
time.sleep(2)
if self.glances_process.poll() is not None:
raise RuntimeError("Glances 启动失败")
print(f"Glances Web 服务已启动: http://{self.host}:{self.port}")
logger.info(f"Glances Web 服务已启动: http://{self.host}:{self.port}")
except subprocess.CalledProcessError:
print("错误: Glances 未安装。请运行: python3.11 -m pip install glances")
logger.error("错误: Glances 未安装。请运行: python3.11 -m pip install glances")
raise
except Exception as e:
print(f"启动 Glances 失败: {e}")
logger.error(f"启动 Glances 失败: {e}")
raise
def stop_glances(self):
@@ -70,7 +72,7 @@ class GlancesMonitor:
if self.glances_process:
self.glances_process.terminate()
self.glances_process.wait()
print("Glances Web 服务已停止")
logger.error("Glances Web 服务已停止")
def send_alert_email(self, metric, value, threshold):
"""发送告警邮件,限制每小时一次"""
@@ -130,10 +132,10 @@ class GlancesMonitor:
time.sleep(10)
except requests.RequestException as e:
print(f"连接 Glances API 失败: {e}")
logger.error(f"连接 Glances API 失败: {e}")
time.sleep(60)
except Exception as e:
print(f"监控错误: {e}")
logger.error(f"监控错误: {e}")
time.sleep(60)
def run(self):