提交 25f9b139 authored 作者: 陈泽健's avatar 陈泽健

调整日志监测模块的文件规范路径,补充相关日志打印。

上级 57f9a879
......@@ -7,7 +7,7 @@ import hmac
import hashlib
import base64
import requests
import hytest
def dingding_send_message(error_message,ding_type):
"""
......
1. 2025-06-05:
- 补充预定系统对内服务日志的日志监测脚本,获取到错误日志信息会进行收集前后文,并调用钉钉消息发送至钉钉群中。
\ No newline at end of file
- 补充预定系统对内服务日志的日志监测脚本,获取到错误日志信息会进行收集前后文,并调用钉钉消息发送至钉钉群中。
- 调整日志监测模块的文件规范路径,补充相关日志打印。
\ No newline at end of file
......@@ -5,19 +5,34 @@ import logging
import sys
import os
# 配置日志输出
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
INFO = logging.info
# 添加 base.py 路径到系统路径中(根据你的实际项目结构调整)
sys.path.append(os.path.abspath(".."))
# 从 base.py 导入钉钉发送函数
from base import dingding_send_message
# 要监控的关键字
ERROR_KEYWORDS = ["ERROR", "Exception"]
# 配置日志输出到控制台
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
logging.getLogger().addHandler(console_handler)
logging.getLogger().setLevel(logging.INFO) # 设置全局日志级别
# 获取当前脚本所在目录
current_dir = os.path.dirname(os.path.abspath(__file__))
print("当前脚本目录:", current_dir)
# 构建正确的 Base 目录路径
base_dir = os.path.normpath(os.path.join(current_dir, "..", "Base"))
print("✅ 正确的 Base 目录路径:", base_dir)
# 添加进系统路径
sys.path.append(base_dir)
# 尝试导入
try:
from base import dingding_send_message
print("✅ 成功导入 base 模块!")
except ImportError as e:
print("❌ 导入失败:", e)
print("🔍 sys.path 中包含的路径如下:")
for p in sys.path:
print(" -", p)
class LogMonitor:
def __init__(self, host, username, private_key_path, passphrase, log_path, check_interval=1):
......@@ -43,15 +58,15 @@ class LogMonitor:
self.client.connect(self.host, username=self.username, pkey=private_key)
self.channel = self.client.invoke_shell()
self.channel.send(f"tail -f {self.log_path}\n")
INFO(f"Connected to {self.host}, monitoring {self.log_path}")
logging.info(f"Connected to {self.host}, monitoring {self.log_path}")
return True
except Exception as e:
INFO(f"连接失败: {e}")
logging.info(f"连接失败: {e}")
return False
def start_monitoring(self):
if self.collecting:
INFO("Already monitoring logs.")
logging.info("Already monitoring logs.")
return
if not self.connect():
......@@ -60,7 +75,7 @@ class LogMonitor:
self.collecting = True
self.monitor_thread = threading.Thread(target=self._monitor_loop)
self.monitor_thread.start()
INFO("开始日志监控...")
logging.info("开始日志监控...")
def stop_monitoring(self):
self.collecting = False
......@@ -68,7 +83,7 @@ class LogMonitor:
self.channel.close()
if self.client:
self.client.close()
INFO("停止日志监控.")
logging.info("停止日志监控.")
def _monitor_loop(self):
try:
......@@ -83,11 +98,11 @@ class LogMonitor:
time.sleep(self.check_interval)
except (paramiko.SSHException, paramiko.socket.error, OSError) as e:
INFO(f"SSH 连接中断: {e}")
logging.info(f"SSH 连接中断: {e}")
self.restart_monitoring()
except Exception as e:
INFO(f"监控过程中发生异常: {e}")
logging.info(f"监控过程中发生异常: {e}")
self.restart_monitoring()
def _process_line(self, line):
......@@ -102,7 +117,7 @@ class LogMonitor:
level = level_part.split()[-1] # 取最后一个词作为日志级别
if level in ["ERROR", "Exception"]:
INFO(f"发现 {level} 日志!正在通过 SSH 获取上下文日志...")
logging.info(f"发现 {level} 日志!正在通过 SSH 获取上下文日志...")
full_log = self.get_remote_log_with_paramiko(
host=self.host,
......@@ -145,20 +160,20 @@ class LogMonitor:
try:
dingding_send_message(message_text, ding_type="标准版服务监测")
except Exception as e:
INFO(f"发送钉钉消息失败: {e}")
logging.info(f"发送钉钉消息失败: {e}")
INFO("上下文日志如下:\n" + "\n".join(context))
logging.info("上下文日志如下:\n" + "\n".join(context))
break
else:
INFO("获取日志失败,无法获取上下文")
logging.error("获取日志失败,无法获取上下文")
except IndexError:
pass
except Exception as e:
INFO(f"获取上下文日志失败: {e}")
logging.exception(f"获取上下文日志失败: {e}")
def restart_monitoring(self):
"""自动重启日志监控"""
INFO("尝试重新启动日志监控...")
logging.info("尝试重新启动日志监控...")
self.stop_monitoring()
time.sleep(5)
self.start_monitoring()
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论