Created
September 10, 2021 15:05
-
-
Save arulrajnet/f8ed114b5b6bc60823b5e83b47aee139 to your computer and use it in GitHub Desktop.
Handling "X-Request-ID" tracing in flask with logger
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
#! /usr/bin/env python3 | |
from flask import Flask, request | |
# Need python 3.7+ | |
from contextvars import ContextVar | |
import logging | |
request_id_context = ContextVar("request_id") | |
# Flask app | |
app = Flask(__name__) | |
@app.route("/") | |
def hello_world(): | |
logging.info("Hello, World!") | |
return "<p>Hello, World!</p>" | |
@app.before_request | |
def before_request(): | |
if request.headers.get('X-Request-ID') is not None: | |
request_id_context.set(request.headers.get('X-Request-ID').strip()) | |
class LoggingFilter(logging.Filter): | |
""" | |
Filter to add request id into the log record. | |
This will read the X_REQUEST_ID from request object and set in log record. | |
""" | |
def filter(self, log_record): | |
log_record.request_id = request_id_context.get("NA") | |
return log_record | |
if __name__ == "__main__": | |
# Setup your logger | |
handler = logging.StreamHandler() | |
handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(request_id)s - %(message)s")) | |
handler.addFilter(LoggingFilter()) | |
logging.getLogger().addHandler(handler) | |
logging.getLogger().setLevel("INFO") | |
app.run('0.0.0.0', 5000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Handing tracing header in flask
This requires python 3.7+. We use contextvars to store the value based on thread.
To start flask server
wget https://gist.githubusercontent.com/arulrajnet/f8ed114b5b6bc60823b5e83b47aee139/raw/flask_tracing_request_id.py
python3 flask_tracing_request_id.py
curl -v -H "x-request-id: $(date +%s)" http://localhost:5000/