Python Flask logging with ID on each Request
Difficulty of debugging strike me when i don’t know which request is each log for. Fortunately, it’s happen on stage. Imagine if it happen on production, my client could run away when they know we couldn’t know how to fix it.
Googling and googling but i still couldn’t find the right way to do so. There’s an extension that could add unique ID on each request which is flask-log-request-id. However, i couldn’t implement it right away based on the documentation. It’s only writing to terminal which is not what i desire.
Enough talking, let’s get working.
- Let's install it on our project.
`pip install flask-log-request-id` - then, on our main.py file implement this code:
# main.py
import logging
import logging.config
from random import randint
from flask import Flask
from flask_log_request_id import RequestID, RequestIDLogFilterdef generic_add(a, b):
"""Simple function to add two numbers that is not aware of the request id"""
logging.debug('Called generic_add({}, {})'.format(a, b))
return a + bapp = Flask(__name__)
RequestID(app)logname = "service.log"
handler = logging.FileHandler(logname) # This is the one that we need to write it to our log file
handler.setFormatter(
logging.Formatter("%(asctime)s:%(levelname)s:%(request_id)s - %(message)s")) # i make the format more compact
handler.addFilter(RequestIDLogFilter()) # << Add request id contextual filterlogging.getLogger().addHandler(handler)@app.route('/')
def index():
a, b = randint(1, 15), randint(1, 15)
logging.info('Adding two random numbers {} {}'.format(a, b))
return str(generic_add(a, b))
3. Run your project python main.py
4. Hit the route with browser http://locahost:5000/
and then service.log
will look like this:
2021-01-19 04:43:52,482:INFO:bcc58751-fd8e-4de7-93c5-0a9bed68ba30 - Adding two random numbers 1 2
2021-01-19 04:43:52,482:INFO:bcc58751-fd8e-4de7-93c5-0a9bed68ba30 - Called generic_add(1, 2)
2021-01-19 04:43:53,482:INFO:5c643f0b-c491-4098-94ee-08758d69de54 - Adding two random numbers 3 4
2021-01-19 04:43:53,482:INFO:5c643f0b-c491-4098-94ee-08758d69de54 - Called generic_add(3, 4)
That’s everything i could share, i hope that’s helpful.