How to log HTTP response in Tornado?

2019-08-06 06:20发布

问题:

I want to be able to log HTTP request and response in tornado. This seems to be easy to do with request:

def log_function(handler):
    info = {
        'Method' : handler.request.method,
        'Host' : handler.request.host,
        'URL' : handler.request.uri
     }

How can the same thing be achieved for response? The response status_code can be retrieved by calling

handler.get_status()

How do I get a body of a response?

回答1:

Tornado doesn't save the response; it sends it directly to the client. If you want to log the response you'll have to save it yourself. You can either do this in your handler code or override the write() and finish() methods to intercept it as it is being written.