tornado利用装饰器记录每个http请求
python利用装饰器记录每个http请求
设置装饰器
from functools import wraps from datetime import datetime """ @function 用于记录每个http请求 """ def record_http_request(func): @wraps(func) def record(self, *args, **kwargs): request_time = str(datetime.now()) response = func(self, *args, **kwargs) http_request = dict( request_time=request_time, expend_time=self.request.request_time(), response_time=str(datetime.now()), request_ip=self.request.remote_ip, method=self.request.method, url=self.request.uri, request_params=self.request.arguments, response_code=self.get_status(), response_text=self.response_value, ) print(http_request) return response return record
然后在每个请求函数上面加上这个装饰器
from abc import ABC from tornado.web import RequestHandler from tornado.gen import coroutine from handler.record_infomation import record_http_request class Index(RequestHandler, ABC): @coroutine @record_http_request def get(self, *args, **kwargs): self.response_value = {"status": 200, "message": "dddd"} self.write(self.response_value)
这个时候我们那就可以看到装饰器中的print值为
{'request_time': '2019-04-06 19:16:54.951968', 'expend_time': 0.000576019287109375, 'response_time': '2019-04-06 19:16:54.952035', 'request_ip': '192.168.0.102', 'method': 'GET', 'url': '/', 'request_params': {}, 'response_code': 200, 'response_text': {'status': 200, 'message': 'dddd'}}
值已经拿到了,是存库还是记录到日志文件就随便了