装饰器,timer  or log

打印日志以及方法运行时间

对于异步方法:

from functools import wraps
import traceback
import time
def async_time_fun(func):
    @wraps(func)
    async def log(*args, **kwargs):
        start = time.time()
        try:
            print(time.strftime("%Y-%m-%d %H:%M:%S") + " start ", func.__name__)
            result = await func(*args, **kwargs)
            print("end " + func.__name__ + " total cost time (s) :", str((time.time() - start)))
            return result
        except Exception as e:
            print(f"{func.__name__} is error,here are details:{traceback.format_exc()}")
            print("end " + func.__name__ + "  total cost time (s) :", str((time.time() - start)))
            return {"status": 500, "message": traceback.format_exc(), "data": None}
    return log

 

对于同步方法


from functools import wraps
import traceback
import time
def timefun(func):
    @wraps(func)
    def log(*args, **kwargs):
        start = time.time()
        try:
            print("start ", func.__name__)
            result = func(*args, **kwargs)
            print("end " + func.__name__ + " total cost time (s) :", str((time.time() - start)))
            return result
        except Exception as e:
            print(f"{func.__name__} is error,here are details:{traceback.format_exc()}")
            print("end " + func.__name__ + " total cost time (s) :", str((time.time() - start)))
            return {"status": 500, "message ": str(traceback.format_exc()), "data": None}
    return log
@timefun
def foo():
    time.sleep(1)
    print("I am foo")

@timefun
def getInfo():
    return '----hahah---'

f = foo()
print(type(f))

 

 

time.strftime('%d-%b-%Y', time.localtime(time.time()))
time.strftime("%Y-%m-%d %H:%M:%S")

python中时间日期格式化符号:

  • %y 两位数的年份表示(00-99)
  • %Y 四位数的年份表示(000-9999)
  • %m 月份(01-12)
  • %d 月内中的一天(0-31)
  • %H 24小时制小时数(0-23)
  • %I 12小时制小时数(01-12)
  • %M 分钟数(00=59)
  • %S 秒(00-59)
  • %a 本地简化星期名称
  • %A 本地完整星期名称
  • %b 本地简化的月份名称
  • %B 本地完整的月份名称
  • %c 本地相应的日期表示和时间表示
  • %j 年内的一天(001-366)
  • %p 本地A.M.或P.M.的等价符
  • %U 一年中的星期数(00-53)星期天为星期的开始
  • %w 星期(0-6),星期天为星期的开始
  • %W 一年中的星期数(00-53)星期一为星期的开始
  • %x 本地相应的日期表示
  • %X 本地相应的时间表示
  • %Z 当前时区的名称
  • %% %号本身
posted on 2019-11-17 16:15  lshan  阅读(388)  评论(0编辑  收藏  举报