From 8f0d13923c714d5e69fd3b594bf2943c57f2a9a2 Mon Sep 17 00:00:00 2001 From: SengokuCola <1026294844@qq.com> Date: Wed, 19 Mar 2025 15:27:53 +0800 Subject: [PATCH] =?UTF-8?q?better=20=E4=BC=98=E5=8C=96logger=E8=BE=93?= =?UTF-8?q?=E5=87=BA=EF=BC=8C=E6=B8=85=E6=B4=81cmd?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bot.py | 2 -- src/common/logger.py | 54 ++++++++++++++++++++++------- src/plugins/chat/bot.py | 12 +++++-- src/plugins/chat/message_sender.py | 4 +-- src/plugins/memory_system/memory.py | 6 ++-- src/plugins/models/utils_model.py | 2 +- src/plugins/utils/typo_generator.py | 2 +- 7 files changed, 59 insertions(+), 23 deletions(-) diff --git a/bot.py b/bot.py index e8f3ae806..741711dcb 100644 --- a/bot.py +++ b/bot.py @@ -14,8 +14,6 @@ from nonebot.adapters.onebot.v11 import Adapter import platform from src.common.logger import get_module_logger - -# 配置主程序日志格式 logger = get_module_logger("main_bot") # 获取没有加载env时的环境变量 diff --git a/src/common/logger.py b/src/common/logger.py index 143fe9f95..0b8e18b98 100644 --- a/src/common/logger.py +++ b/src/common/logger.py @@ -7,7 +7,9 @@ from pathlib import Path from dotenv import load_dotenv # from ..plugins.chat.config import global_config -load_dotenv() +# 加载 .env.prod 文件 +env_path = Path(__file__).resolve().parent.parent.parent / '.env.prod' +load_dotenv(dotenv_path=env_path) # 保存原生处理器ID default_handler_id = None @@ -29,8 +31,6 @@ _handler_registry: Dict[str, List[int]] = {} current_file_path = Path(__file__).resolve() LOG_ROOT = "logs" -# 从环境变量获取是否启用高级输出 -# ENABLE_ADVANCE_OUTPUT = True ENABLE_ADVANCE_OUTPUT = False if ENABLE_ADVANCE_OUTPUT: @@ -82,8 +82,6 @@ else: "compression": "zip", } -# 控制nonebot日志输出的环境变量 -NONEBOT_LOG_ENABLED = False # 海马体日志样式配置 MEMORY_STYLE_CONFIG = { @@ -185,8 +183,7 @@ LLM_STYLE_CONFIG = { ) } } - - + # Topic日志样式配置 TOPIC_STYLE_CONFIG = { @@ -222,15 +219,47 @@ TOPIC_STYLE_CONFIG = { } } +# Topic日志样式配置 +CHAT_STYLE_CONFIG = { + "advanced": { + "console_format": ( + "{time:YYYY-MM-DD HH:mm:ss} | " + "{level: <8} | " + "{extra[module]: <12} | " + "见闻 | " + "{message}" + ), + "file_format": ( + "{time:YYYY-MM-DD HH:mm:ss} | " + "{level: <8} | " + "{extra[module]: <15} | " + "见闻 | " + "{message}" + ) + }, + "simple": { + "console_format": ( + "{time:MM-DD HH:mm} | " + "见闻 | " + "{message}" + ), + "file_format": ( + "{time:YYYY-MM-DD HH:mm:ss} | " + "{level: <8} | " + "{extra[module]: <15} | " + "见闻 | " + "{message}" + ) + } +} + # 根据ENABLE_ADVANCE_OUTPUT选择配置 MEMORY_STYLE_CONFIG = MEMORY_STYLE_CONFIG["advanced"] if ENABLE_ADVANCE_OUTPUT else MEMORY_STYLE_CONFIG["simple"] TOPIC_STYLE_CONFIG = TOPIC_STYLE_CONFIG["advanced"] if ENABLE_ADVANCE_OUTPUT else TOPIC_STYLE_CONFIG["simple"] SENDER_STYLE_CONFIG = SENDER_STYLE_CONFIG["advanced"] if ENABLE_ADVANCE_OUTPUT else SENDER_STYLE_CONFIG["simple"] LLM_STYLE_CONFIG = LLM_STYLE_CONFIG["advanced"] if ENABLE_ADVANCE_OUTPUT else LLM_STYLE_CONFIG["simple"] +CHAT_STYLE_CONFIG = CHAT_STYLE_CONFIG["advanced"] if ENABLE_ADVANCE_OUTPUT else CHAT_STYLE_CONFIG["simple"] -def filter_nonebot(record: dict) -> bool: - """过滤nonebot的日志""" - return record["extra"].get("module") != "nonebot" def is_registered_module(record: dict) -> bool: """检查是否为已注册的模块""" @@ -335,6 +364,7 @@ def remove_module_logger(module_name: str) -> None: # 添加全局默认处理器(只处理未注册模块的日志--->控制台) +# print(os.getenv("DEFAULT_CONSOLE_LOG_LEVEL", "SUCCESS")) DEFAULT_GLOBAL_HANDLER = logger.add( sink=sys.stderr, level=os.getenv("DEFAULT_CONSOLE_LOG_LEVEL", "SUCCESS"), @@ -344,7 +374,7 @@ DEFAULT_GLOBAL_HANDLER = logger.add( "{name: <12} | " "{message}" ), - filter=lambda record: is_unregistered_module(record) and filter_nonebot(record), # 只处理未注册模块的日志,并过滤nonebot + filter=lambda record: is_unregistered_module(record), # 只处理未注册模块的日志,并过滤nonebot enqueue=True, ) @@ -367,6 +397,6 @@ DEFAULT_FILE_HANDLER = logger.add( retention=DEFAULT_CONFIG["retention"], compression=DEFAULT_CONFIG["compression"], encoding="utf-8", - filter=lambda record: is_unregistered_module(record) and filter_nonebot(record), # 只处理未注册模块的日志,并过滤nonebot + filter=lambda record: is_unregistered_module(record), # 只处理未注册模块的日志,并过滤nonebot enqueue=True, ) diff --git a/src/plugins/chat/bot.py b/src/plugins/chat/bot.py index ec845fedf..23f3959ea 100644 --- a/src/plugins/chat/bot.py +++ b/src/plugins/chat/bot.py @@ -12,7 +12,6 @@ from nonebot.adapters.onebot.v11 import ( FriendRecallNoticeEvent, ) -from src.common.logger import get_module_logger from ..memory_system.memory import hippocampus from ..moods.moods import MoodManager # 导入情绪管理器 from .config import global_config @@ -33,7 +32,16 @@ from .utils_user import get_user_nickname, get_user_cardname, get_groupname from ..willing.willing_manager import willing_manager # 导入意愿管理器 from .message_base import UserInfo, GroupInfo, Seg -logger = get_module_logger("chat_bot") +from src.common.logger import get_module_logger, CHAT_STYLE_CONFIG, LogConfig +# 定义日志配置 +chat_config = LogConfig( + # 使用消息发送专用样式 + console_format=CHAT_STYLE_CONFIG["console_format"], + file_format=CHAT_STYLE_CONFIG["file_format"] +) + +# 配置主程序日志格式 +logger = get_module_logger("chat_bot", config=chat_config) class ChatBot: diff --git a/src/plugins/chat/message_sender.py b/src/plugins/chat/message_sender.py index 936e7f8d0..e71d10e49 100644 --- a/src/plugins/chat/message_sender.py +++ b/src/plugins/chat/message_sender.py @@ -69,7 +69,7 @@ class Message_Sender: message=message_send.raw_message, auto_escape=False, ) - logger.success(f"[调试] 发送消息“{message_preview}”成功") + logger.success(f"发送消息“{message_preview}”成功") except Exception as e: logger.error(f"[调试] 发生错误 {e}") logger.error(f"[调试] 发送消息“{message_preview}”失败") @@ -81,7 +81,7 @@ class Message_Sender: message=message_send.raw_message, auto_escape=False, ) - logger.success(f"[调试] 发送消息“{message_preview}”成功") + logger.success(f"发送消息“{message_preview}”成功") except Exception as e: logger.error(f"[调试] 发生错误 {e}") logger.error(f"[调试] 发送消息“{message_preview}”失败") diff --git a/src/plugins/memory_system/memory.py b/src/plugins/memory_system/memory.py index ece0981dc..cd7f18eb1 100644 --- a/src/plugins/memory_system/memory.py +++ b/src/plugins/memory_system/memory.py @@ -826,7 +826,7 @@ class Hippocampus: async def memory_activate_value(self, text: str, max_topics: int = 5, similarity_threshold: float = 0.3) -> int: """计算输入文本对记忆的激活程度""" - logger.info(f"[激活] 识别主题: {await self._identify_topics(text)}") + logger.info(f"识别主题: {await self._identify_topics(text)}") # 识别主题 identified_topics = await self._identify_topics(text) @@ -858,7 +858,7 @@ class Hippocampus: activation = int(score * 50 * penalty) logger.info( - f"[激活] 单主题「{topic}」- 相似度: {score:.3f}, 内容数: {content_count}, 激活值: {activation}") + f"单主题「{topic}」- 相似度: {score:.3f}, 内容数: {content_count}, 激活值: {activation}") return activation # 计算关键词匹配率,同时考虑内容数量 @@ -895,7 +895,7 @@ class Hippocampus: # 计算最终激活值 activation = int((topic_match + average_similarities) / 2 * 100) logger.info( - f"[激活] 匹配率: {topic_match:.3f}, 平均相似度: {average_similarities:.3f}, 激活值: {activation}") + f"匹配率: {topic_match:.3f}, 平均相似度: {average_similarities:.3f}, 激活值: {activation}") return activation diff --git a/src/plugins/models/utils_model.py b/src/plugins/models/utils_model.py index 0764a1949..3d4bd818d 100644 --- a/src/plugins/models/utils_model.py +++ b/src/plugins/models/utils_model.py @@ -103,7 +103,7 @@ class LLM_request: "timestamp": datetime.now(), } db.llm_usage.insert_one(usage_data) - logger.info( + logger.debug( f"Token使用情况 - 模型: {self.model_name}, " f"用户: {user_id}, 类型: {request_type}, " f"提示词: {prompt_tokens}, 完成: {completion_tokens}, " diff --git a/src/plugins/utils/typo_generator.py b/src/plugins/utils/typo_generator.py index 1cf09bdf3..fc776b0fa 100644 --- a/src/plugins/utils/typo_generator.py +++ b/src/plugins/utils/typo_generator.py @@ -42,7 +42,7 @@ class ChineseTypoGenerator: # 加载数据 # print("正在加载汉字数据库,请稍候...") - logger.info("正在加载汉字数据库,请稍候...") + # logger.info("正在加载汉字数据库,请稍候...") self.pinyin_dict = self._create_pinyin_dict() self.char_frequency = self._load_or_create_char_frequency()