importasynciofromtyping_extensionsimportTYPE_CHECKING,Any,AsyncGenerator,NotRequired,TypedDict,castfrom.reflectimportloggerifTYPE_CHECKING:importsocketfrom.._runimportset_loop_exc_handlerfrom..typimportExitCode,LogLevelclassLoopExcCtx(TypedDict):message:strexception:NotRequired[BaseException]future:NotRequired[asyncio.Future]task:NotRequired[asyncio.Task]handle:NotRequired[asyncio.Handle]protocol:NotRequired[asyncio.Protocol]transport:NotRequired[asyncio.Transport]socket:NotRequired["socket.socket"]asyncgen:NotRequired[AsyncGenerator]_STRICT_LOOP_LOG=Falsedefset_loop_exc_log(strict:bool)->None:global_STRICT_LOOP_LOG_STRICT_LOOP_LOG=strictdef_log_loop_exception(loop:asyncio.AbstractEventLoop,context:dict[str,Any])->None:ctx=cast(LoopExcCtx,context)with_loop_ctx={"loop":loop}|ctxexc=ctx.get("exception")msg=ctx["message"]ifexcisnotNone:if(isinstance(exc,SystemExit)andexc.codeisnotNoneandint(exc.code)==ExitCode.RESTART.value):logger.debug("收到重启信号,即将重启...")elif"exception was never retrieved"inmsg:fut=ctx.get("future")task=ctx.get("task")if_STRICT_LOOP_LOG:try:raiseexcexceptBaseException:logger.exception(f"从未捕获的异常的回溯栈:{msg}")logger.generic_obj(f"发现从未捕获的异常(这不一定是错误):{msg}",{"future":fut,"task":task},level=LogLevel.ERRORif_STRICT_LOOP_LOGelseLogLevel.DEBUG,)else:try:raiseexcexceptBaseException:logger.exception(f"事件循环中抛出预期外的异常:{msg}")logger.generic_obj("相关变量信息:",with_loop_ctx,level=LogLevel.ERROR)else:logger.error(f"事件循环出现预期外的状况:{msg}")logger.generic_obj("相关变量信息:",with_loop_ctx,level=LogLevel.ERROR)set_loop_exc_handler(_log_loop_exception)