Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
[Python tornado logging when request has completed] #python #python3 #tornado #logging #logs #server #http
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.
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.