44 lines
1.4 KiB
Python
44 lines
1.4 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""日志装饰器 @setLog():记录用例方法拿到的接口返回。
|
|
|
|
两个要点:
|
|
1. 装饰器模式,用例方法加一行即可记录返回,不侵入业务代码;
|
|
2. 需要 json.dumps(...).encode().decode('unicode_escape') 中文转码,
|
|
否则日志里的中文会写成 unicode 转义序列(形如反斜杠 u 加四位十六进制)。
|
|
日志落 artifacts/logs/(已 gitignore)。
|
|
"""
|
|
import functools
|
|
import json
|
|
import logging
|
|
from datetime import datetime
|
|
|
|
from core.path import artifact_path
|
|
|
|
_LOG_FILE = artifact_path('logs', 'log_{0}.log'.format(datetime.now().strftime('%Y-%m-%d')))
|
|
|
|
logging.basicConfig(
|
|
filename=_LOG_FILE,
|
|
filemode='a',
|
|
level=logging.DEBUG,
|
|
format='%(asctime)s - %(levelname)s - %(message)s',
|
|
datefmt='%m/%d/%Y %H:%M:%S %p',
|
|
)
|
|
|
|
|
|
def setLog():
|
|
"""装饰器:把被装饰函数的返回值以 info 级写入日志,异常写 error。"""
|
|
def get_func(func):
|
|
@functools.wraps(func)
|
|
def get_args(*args, **kwargs):
|
|
try:
|
|
temp = func(*args, **kwargs)
|
|
# 中文转码:否则日志里的中文会写成 \uXXXX
|
|
msg = json.dumps(temp, ensure_ascii=True).encode('utf-8').decode('unicode_escape')
|
|
logging.info(msg)
|
|
return temp
|
|
except Exception as e:
|
|
logging.error(repr(e))
|
|
raise
|
|
return get_args
|
|
return get_func
|