问题描述
我正在使用默认的cherrypy 记录器。 我已经记录了对我的服务器的每个访问请求。对于 GET 请求,我有完整的信息,比如
- command: "{{ item }}"
loop:
- "ls"
- "df -h"
register: files
- command: "{{ item }}"
loop:
- "ls -lrt"
- "du -h"
register: files1
- lineinfile:
line: "{{ item.stdout }}"
path: /home/ubuntu/log/list.log
create: yes
loop:
- "{{ files.results }}"
- "{{ files1.results }}"
delegate_to: localhost
但是对于 POST 请求,我无法记录查询参数或正文。
127.0.0.1 - - [06/Jul/2021:16:10:28] "GET /test/?contract_id=228322 HTTP/1.0" 200 33
那么我如何记录 POST 查询的正文?
解决方法
您可以创建类似的工具
def response_logging():
cherrypy.log.access_log.info(
'[{time}] {ip} "{user_agent}" {request_line} "{query_params}" "{body}" "{status}" {response}'.format(
time=datetime.now().strftime("%d/%m/%Y:%H:%M:%S"),ip=cherrypy.request.remote.ip,user_agent=cherrypy.request.headers["User-Agent"],request_line=cherrypy.request.request_line,query_params=cherrypy.request.body.request_params or "",body=cherrypy.request.json if hasattr(cherrypy.request,"json") else "",status=cherrypy.response.status,response=cherrypy.response.body
)
)
cherrypy.tools.response_logging = cherrypy.Tool('on_end_request',response_logging)
,
print(cherrypy.request.params) # Prints params on querystring
print(cherrypy.request.headers) # Prints received headers on request
print(cherrypy.request.body) # Prints Body received