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

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

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