Last active
September 28, 2020 08:35
-
-
Save Integralist/428cb45b94290c72adc5c9e5af27a58f to your computer and use it in GitHub Desktop.
[Python tornado logging when request has completed] #python #python3 #tornado #logging #logs #server #http
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
That Application.log_request approach uses very explicit naming, | |
and yet the tornado docs for RequestHandler.on_finish says... | |
> Override this method to perform cleanup, logging, etc. | |
So there’s two ways to essentially do the same thing 🤔 | |
My understanding for the difference would be log_request is useful for | |
generic logging behaviour, while on_finish could be customized per | |
request handler. | |
NOTE: log_request completes first, then on_finish | |
""" | |
import asyncio | |
import tornado.ioloop | |
import tornado.web | |
class MainHandler(tornado.web.RequestHandler): | |
def initialize(self, *args, **kwargs): | |
print("initialize:", args, kwargs) | |
def prepare(self): | |
self.ctx = {} | |
print("prepare:", self.ctx) | |
async def get(self): | |
self.write("Hello, world") | |
self.ctx["abc"] = 123 | |
await asyncio.sleep(2) | |
print("get:", self.ctx) | |
def on_finish(self): | |
self.ctx["xyz"] = 456 | |
print("finish:", self.ctx) | |
def make_app(): | |
class App(tornado.web.Application): | |
"""subclass tornado web application so we can override log_request. | |
DOCUMENTATION: | |
https://www.tornadoweb.org/en/stable/web.html#tornado.web.Application.log_request | |
""" | |
def log_request(self, handler: tornado.web.RequestHandler) -> None: | |
print("log stuff") | |
# return tornado.web.Application([ | |
# (r'/', MainHandler, {"beep": 123, "boop": 456}), | |
# ]) | |
return App([ | |
(r'/', MainHandler, {"beep": 123, "boop": 456}), | |
]) | |
if __name__ == '__main__': | |
app = make_app() | |
app.listen(9000) | |
tornado.ioloop.IOLoop.current().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment