python装饰器实现HTTP请求耗时和入参返回日志记录
装饰器方法:
1 def decoArgs(server_name): 2 def deco(func): 3 def wrapper(view, request, *args, **kwargs): 4 startTime = time.time() 5 resp = None 6 try: 7 resp = func(view, request, args, kwargs) 8 finally: 9 endTime = time.time() 10 cost = (endTime - startTime)*1000 11 12 msg = None 13 code = None 14 try: 15 resp_data = json.loads(resp.content) 16 msg = resp_data.get("msg") 17 code = resp_data.get("code") 18 except Exception: 19 pass 20 21 log(server_name, code, cost, msg, request.GET) 22 return resp 23 return wrapper 24 return deco
使用装饰器:
1 from django.views.generic import View 2 class MyView(View): 3 4 @decoArgs("my_server") 5 def get(self, request, *args, **kwargs): 6 return JsonResp(0, "ok", resp)