You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
95 lines
2.8 KiB
95 lines
2.8 KiB
import os
|
|
|
|
import requests
|
|
from loguru import logger
|
|
import inspect
|
|
from functools import wraps
|
|
|
|
cwd = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
print(cwd)
|
|
logger.add(f"{cwd}/my.log", # log文件地址
|
|
level="DEBUG", # log记录最低级别
|
|
rotation="00:00", # 将日志记录以大小、时间等方式进行分割或划分
|
|
retention="3 days", # 文件保留时间
|
|
compression="zip", # 文件压缩格式
|
|
backtrace=True,
|
|
# rotation="1 MB" # 滚动大日志文件
|
|
|
|
)
|
|
LOGGER = logger
|
|
|
|
|
|
def send_mag(content):
|
|
for i in range(3):
|
|
try:
|
|
url = 'https://jdtbpdd.cn/wx/send_msg?'
|
|
data = {'content': content}
|
|
res = requests.post(url, data=data).json()
|
|
logger.info(f'消息发送结果:{res}')
|
|
return res
|
|
except Exception as e:
|
|
logger.error(f'推送消息异常:{e}')
|
|
return None
|
|
|
|
|
|
def _get_caller_info():
|
|
frame = inspect.currentframe()
|
|
try:
|
|
caller = frame.f_back.f_back # 跳过 wrapper 自身
|
|
return f"{caller.f_code.co_filename}:{caller.f_lineno}"
|
|
finally:
|
|
del frame
|
|
|
|
|
|
def retry(name='备注', log=True, result_log=False, over_msg=False, error_msg=True):
|
|
"""
|
|
|
|
:param name:
|
|
:param log: 日志是否打印
|
|
:param result_log: 返回结果日志是否打印
|
|
:param over_msg: 成功是否推送
|
|
:param error_msg: 失败是否推送
|
|
:return:
|
|
"""
|
|
|
|
def retry_fun(fun):
|
|
@wraps(fun)
|
|
def wrapper(*args, **kwargs):
|
|
|
|
caller_info = _get_caller_info() if log else ""
|
|
|
|
if log:
|
|
logger.info(f"[{name}] 开始: {caller_info}")
|
|
|
|
try:
|
|
result = fun(*args, **kwargs)
|
|
if log:
|
|
if result_log:
|
|
logger.info(f"[{name}] 调用成功: {caller_info} result:{str(result)}")
|
|
else:
|
|
logger.info(f"[{name}] 调用成功: {caller_info}")
|
|
if over_msg:
|
|
send_mag(f"[{name}] 调用成功:\n[执行程序]:{caller_info}\n[返回结果]:{str(result)}")
|
|
return result
|
|
except Exception as e:
|
|
if log:
|
|
logger.exception(f"[{name}] 异常调用: {caller_info} - {e}")
|
|
else:
|
|
logger.exception(f"[{name}] 异常: {e}")
|
|
if error_msg:
|
|
send_mag(f"[{name}]: 异常调用:\n[执行程序]:{caller_info}\n[异常内容]:{e}")
|
|
# raise # ⚠️ 强烈建议保留(否则异常被吞掉)
|
|
|
|
return wrapper
|
|
|
|
return retry_fun
|
|
|
|
|
|
@retry(name='测试', over_msg=True)
|
|
def test():
|
|
|
|
return 'mytest'
|
|
|
|
|
|
if __name__ == '__main__':
|
|
test()
|