Qwen2.5-7B多语言混输:混合语言处理
2026/1/10 4:55:58
@浙大疏锦行
作业:编写一个装饰器logger,在函数执行前后打印日志信息
# 导入必要模块,functools.wraps用于保留被装饰函数的元信息 import functools from datetime import datetime def logger(func): """ 日志装饰器:在函数执行前后打印相关日志信息 :param func: 被装饰的函数 :return: 包装后的函数 """ # 使用functools.wraps装饰内层函数,保留原函数的__name__、__doc__等元信息 @functools.wraps(func) def wrapper(*args, **kwargs): """内层包装函数,实现日志打印逻辑""" # 1. 函数执行前:打印前置日志 func_name = func.__name__ # 获取原函数名 current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 获取当前格式化时间 print(f"[{current_time}] 开始执行函数:{func_name}()") print(f"[{current_time}] 函数{func_name}的位置参数:{args}") print(f"[{current_time}] 函数{func_name}的关键字参数:{kwargs}") # 2. 执行原函数,保存返回值(兼容有返回值的函数) try: result = func(*args, **kwargs) except Exception as e: # 捕获函数执行异常并打印 print(f"[{current_time}] 函数{func_name}执行失败,异常信息:{str(e)}") raise # 重新抛出异常,不影响原函数的异常传播 else: # 3. 函数执行成功后:打印后置日志 print(f"[{current_time}] 函数{func_name}执行完成,返回结果:{result}") return result # 返回原函数的执行结果 return wrapper