From 3539180362a7c735bfaf541b0b77f9c80da4a771 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=96=87=E8=96=87=E5=AE=89?= Date: Mon, 16 Feb 2026 17:15:06 +0800 Subject: [PATCH] =?UTF-8?q?feat(main):=20=E6=B7=BB=E5=8A=A0=E8=87=AA?= =?UTF-8?q?=E5=AE=9A=E4=B9=89=20asyncio=20=E5=BC=82=E5=B8=B8=E5=A4=84?= =?UTF-8?q?=E7=90=86=E5=99=A8=E4=BB=A5=E4=BC=98=E5=8C=96=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 在主函数中引入自定义的 asyncio 异常处理器,确保在 WebSocket 连接关闭时的 ping 操作不会产生错误日志。此改动提升了系统的日志可读性,避免了不必要的错误信息输出,同时保持了对其他异常的标准处理方式。 --- trading_system/main.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/trading_system/main.py b/trading_system/main.py index 5d3a548..8e6a991 100644 --- a/trading_system/main.py +++ b/trading_system/main.py @@ -4,6 +4,7 @@ import asyncio import logging import sys +import traceback from pathlib import Path # 启动方式兼容(更鲁棒): @@ -119,8 +120,31 @@ except Exception: logger = logging.getLogger(__name__) +def _asyncio_exception_handler(loop, context): + """自定义 asyncio 异常处理器:将 WebSocket 关闭时的 ping 写入异常降级为 DEBUG,避免刷 ERROR。""" + exc = context.get("exception") + if exc is not None and isinstance(exc, ConnectionResetError): + msg = str(exc).lower() + if "closing transport" in msg or "cannot write" in msg: + logger.debug("WebSocket 连接关闭时 ping 已结束(可忽略): %s", exc) + return + # 其他「Task exception was never retrieved」按 asyncio 默认方式记录 + asyncio_logger = logging.getLogger("asyncio") + asyncio_logger.error("Task exception was never retrieved") + if "exception" in context: + asyncio_logger.error("".join(traceback.format_exception(context["exception"]))) + elif "message" in context: + asyncio_logger.error(context["message"]) + + async def main(): """主函数""" + # 设置 asyncio 未检索异常的处理器(避免 aiohttp WebSocket ping 在连接关闭时刷 ERROR) + try: + asyncio.get_running_loop().set_exception_handler(_asyncio_exception_handler) + except RuntimeError: + pass # 无运行中 loop 时忽略 + logger.info("=" * 60) logger.info("币安自动交易系统启动") logger.info("=" * 60)