import traceback,sys from Log4p.core import * Mainlogger = LogManager().GetLogger("MainThread") def format_java_stack_trace(exctype, value, tb, nested=False): tb_list = traceback.extract_tb(tb) if nested: exception_info = f"{exctype.__name__}: {value}\n" else: exception_info = f"Exception has occurred: {exctype.__name__}: {value}\n" for filename, lineno, funcname, line in tb_list: exception_info += f" at {funcname} ({filename}:{lineno})\n" # 检查是否有原因和其他信息 cause = getattr(value, '__cause__', None) context = getattr(value, '__context__', None) if cause: exception_info += "Caused by: " exception_info += format_java_stack_trace(type(cause), cause, cause.__traceback__, nested=True) if context: exception_info += "Suppressed: " exception_info += format_java_stack_trace(type(context), context, context.__traceback__, nested=True) return exception_info def exception_hook(exctype, value, tb): # 获取回溯信息并格式化为字符串 tb_str = format_java_stack_trace(exctype, value, tb) # 记录异常信息到日志 exception_info = "发生异常:\n" exception_info += tb_str Mainlogger.critical(exception_info) sys.excepthook = exception_hook