Files
personal-experiment/advanced_monitor.py
T
2026-03-06 17:07:57 +08:00

146 lines
4.9 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
高级网络监控模块
集成日志和通知功能的高级监控器
"""
from typing import Optional
from network_monitor import NetworkMonitor, MonitorObserver, PingResult
from logger import Logger
from notifier import NotificationManager, NotificationBuilder, ConsoleNotifier
class LoggingObserver(MonitorObserver):
"""日志观察者"""
def __init__(self, logger: Logger):
"""
初始化日志观察者
Args:
logger: 日志记录器
"""
self.logger = logger
def on_ping(self, result: PingResult) -> None:
"""Ping事件回调"""
self.logger.log_ping(
result.success,
result.latency_ms,
result.error_message
)
def on_status_change(self, is_connected: bool, duration: Optional[float] = None) -> None:
"""状态变化事件回调"""
status = "connected" if is_connected else "disconnected"
self.logger.log_status_change(status, duration)
def on_shutdown(self, reason: str) -> None:
"""关机事件回调"""
self.logger.log_shutdown(reason)
class NotificationObserver(MonitorObserver):
"""通知观察者"""
def __init__(self, notification_manager: NotificationManager, notify_interval: int = 10):
"""
初始化通知观察者
Args:
notification_manager: 通知管理器
notify_interval: 通知间隔(秒)
"""
self.notification_manager = notification_manager
self.notify_interval = notify_interval
self.last_notification_time: Optional[float] = None
def on_status_change(self, is_connected: bool, duration: Optional[float] = None) -> None:
"""状态变化事件回调"""
if not is_connected and duration is not None:
# 每隔一定时间发送一次通知
if int(duration) % self.notify_interval == 0 and duration > 0:
self.notification_manager.notify_connection_lost("", duration)
def on_shutdown(self, reason: str) -> None:
"""关机事件回调"""
self.notification_manager.notify_shutdown(reason)
class AdvancedNetworkMonitor(NetworkMonitor):
"""高级网络监控器(装饰器模式)"""
def __init__(self, config=None, enable_logging=True, enable_notifications=True):
"""
初始化高级网络监控器
Args:
config: 监控配置
enable_logging: 是否启用日志
enable_notifications: 是否启用通知
"""
super().__init__(config)
# 初始化日志
self.logger: Optional[Logger] = None
if enable_logging:
self.logger = Logger(
log_dir=self.config.log_dir,
max_log_files=self.config.max_log_files
)
self.add_observer(LoggingObserver(self.logger))
print(f"[{self._get_timestamp()}] 日志功能已启用")
# 初始化通知
self.notification_manager: Optional[NotificationManager] = None
if enable_notifications:
builder = NotificationBuilder()
builder.enable_console(True)
if self.config.enable_desktop_notifications:
builder.enable_desktop(True)
self.notification_manager = builder.build()
notify_interval = max(5, self.config.delay_threshold // 3)
self.add_observer(NotificationObserver(
self.notification_manager,
notify_interval
))
print(f"[{self._get_timestamp()}] 通知功能已启用")
print("-" * 60)
def _stop_by_user(self) -> None:
"""用户中断停止"""
super()._stop_by_user()
if self.logger:
stats = self.logger.get_statistics()
print(f"[{self._get_timestamp()}] 日志统计:")
print(f" - 总事件数: {stats['total_events']}")
print(f" - 总ping次数: {stats['total_pings']}")
print(f" - 成功率: {stats['success_rate']}")
log_file = self.logger.save()
print(f"[{self._get_timestamp()}] 日志已保存到: {log_file}")
def _stop_by_error(self, error: Exception) -> None:
"""错误停止"""
super()._stop_by_error(error)
if self.logger:
self.logger.log_error("MonitorError", str(error))
log_file = self.logger.save()
print(f"[{self._get_timestamp()}] 日志已保存到: {log_file}")
def _trigger_shutdown(self) -> None:
"""触发关机"""
super()._trigger_shutdown()
if self.logger:
log_file = self.logger.save()
print(f"[{self._get_timestamp()}] 日志已保存到: {log_file}")