加入装饰器,进行指令数据统计

This commit is contained in:
liuwei
2025-03-19 12:00:01 +08:00
parent e5a6d09cf9
commit 63c2d4c816

View File

@@ -1,6 +1,7 @@
import functools import functools
import time import time
import traceback import traceback
import logging
from datetime import datetime from datetime import datetime
from typing import Callable, Dict, Any, Tuple from typing import Callable, Dict, Any, Tuple
@@ -17,72 +18,99 @@ def plugin_stats_decorator(plugin_name: str) -> Callable:
Returns: Returns:
装饰器函数 装饰器函数
""" """
# 获取日志记录器
logger = logging.getLogger(f"StatsCollector.{plugin_name}")
logger.info(f"为插件 '{plugin_name}' 应用统计装饰器")
def decorator(func: Callable) -> Callable: def decorator(func: Callable) -> Callable:
logger.info(f"装饰 '{plugin_name}'{func.__name__} 方法")
@functools.wraps(func) @functools.wraps(func)
def wrapper(self, message: Dict[str, Any]) -> Tuple[bool, str]: def wrapper(self, message: Dict[str, Any]) -> Tuple[bool, str]:
# 获取数据库连接 # 获取数据库连接
db_manager = DBConnectionManager.get_instance()
stats_db = StatsDBOperator(db_manager)
# 提取消息信息
content = message.get("content", "")
sender = message.get("sender", "")
roomid = message.get("roomid", "")
# 记录开始时间
start_time = time.time()
try: try:
# 调用原始方法 logger.debug(f"[{plugin_name}] 开始处理消息")
success, response = func(self, message) db_manager = DBConnectionManager.get_instance()
stats_db = StatsDBOperator(db_manager)
# 计算执行时间(毫秒) # 提取消息信息
process_time_ms = (time.time() - start_time) * 1000 content = message.get("content", "")
sender = message.get("sender", "")
roomid = message.get("roomid", "")
# 记录插件调用 logger.debug(f"[{plugin_name}] 消息内容: '{content}', 发送者: {sender}, 群ID: {roomid}")
stats_db.record_plugin_call(
plugin_name=plugin_name,
command=content,
user_id=sender,
group_id=roomid,
success=success,
process_time_ms=process_time_ms
)
return success, response # 记录开始时间
except Exception as e: start_time = time.time()
# 计算执行时间(毫秒) logger.debug(f"[{plugin_name}] 开始执行时间: {datetime.fromtimestamp(start_time).strftime('%Y-%m-%d %H:%M:%S.%f')}")
process_time_ms = (time.time() - start_time) * 1000
# 记录错误
error_message = str(e)
stack_trace = traceback.format_exc()
try: try:
# 记录插件调用(失败) # 调用原始方法
logger.debug(f"[{plugin_name}] 调用原始方法 {func.__name__}")
success, response = func(self, message)
# 计算执行时间(毫秒)
end_time = time.time()
process_time_ms = (end_time - start_time) * 1000
logger.debug(f"[{plugin_name}] 执行完成,耗时: {process_time_ms:.2f}ms, 结果: {success}, 响应: {response}")
# 记录插件调用
logger.debug(f"[{plugin_name}] 记录插件调用统计")
stats_db.record_plugin_call( stats_db.record_plugin_call(
plugin_name=plugin_name, plugin_name=plugin_name,
command=content, command=content,
user_id=sender, user_id=sender,
group_id=roomid, group_id=roomid,
success=False, success=success,
process_time_ms=process_time_ms process_time_ms=process_time_ms
) )
logger.info(f"[{plugin_name}] 成功记录插件调用: {content}, 耗时: {process_time_ms:.2f}ms")
# 记录错误详情 return success, response
stats_db.record_error( except Exception as e:
plugin_name=plugin_name, # 计算执行时间(毫秒)
command=content, end_time = time.time()
user_id=sender, process_time_ms = (end_time - start_time) * 1000
group_id=roomid,
error_message=error_message, # 记录错误
stack_trace=stack_trace error_message = str(e)
) stack_trace = traceback.format_exc()
except Exception as db_error: logger.error(f"[{plugin_name}] 执行出错: {error_message}")
print(f"记录插件统计数据失败: {db_error}") logger.debug(f"[{plugin_name}] 错误堆栈: {stack_trace}")
# 重新抛出异常,让上层处理 try:
raise # 记录插件调用(失败)
logger.debug(f"[{plugin_name}] 记录插件调用失败统计")
stats_db.record_plugin_call(
plugin_name=plugin_name,
command=content,
user_id=sender,
group_id=roomid,
success=False,
process_time_ms=process_time_ms
)
# 记录错误详情
logger.debug(f"[{plugin_name}] 记录错误详情")
stats_db.record_error(
plugin_name=plugin_name,
command=content,
user_id=sender,
group_id=roomid,
error_message=error_message,
stack_trace=stack_trace
)
logger.info(f"[{plugin_name}] 成功记录插件错误: {content}, 错误: {error_message}")
except Exception as db_error:
logger.error(f"[{plugin_name}] 记录插件统计数据失败: {db_error}")
# 重新抛出异常,让上层处理
raise
except Exception as outer_error:
logger.error(f"[{plugin_name}] 装饰器外层错误: {outer_error}")
logger.error(traceback.format_exc())
# 确保原始函数仍然被调用,即使装饰器出错
return func(self, message)
return wrapper return wrapper