All Projects → Workable → Flask Log Request Id

Workable / Flask Log Request Id

Licence: mit
Flask extension to track and log Request-ID headers produced by PaaS like Heroku and load balancers like Amazon ELB

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to Flask Log Request Id

Wechat Admin
Wechat Management System
Stars: ✭ 1,716 (+2018.52%)
Mutual labels:  flask, celery
Enferno
A Python framework based on Flask microframework, with batteries included, and best practices in mind.
Stars: ✭ 385 (+375.31%)
Mutual labels:  flask, celery
Tedivms Flask
Flask starter app with celery, bootstrap, and docker environment
Stars: ✭ 142 (+75.31%)
Mutual labels:  flask, celery
Docker Flask Celery Redis
Docker-Compose template for orchestrating a Flask app with a Celery queue using Redis
Stars: ✭ 165 (+103.7%)
Mutual labels:  flask, celery
Python Devops
gathers Python stack for DevOps, these are usually my basic templates use for my implementations, so, feel free to use it and evolve it! Everything is Docker!
Stars: ✭ 61 (-24.69%)
Mutual labels:  flask, celery
Flask Full
starter/boilerplate flask application with celery, mongoengine, signals, shell commands, swagger api docs and sphinx docs integration
Stars: ✭ 117 (+44.44%)
Mutual labels:  flask, celery
Gather Deployment
Gathers scalable tensorflow and infrastructure deployment
Stars: ✭ 326 (+302.47%)
Mutual labels:  flask, celery
Incepiton Mysql
🍭A web platform designed for mysql inception
Stars: ✭ 90 (+11.11%)
Mutual labels:  flask, celery
Bibi
An e-commerce fullstack solution for Flask 出口电商全栈解决方案
Stars: ✭ 914 (+1028.4%)
Mutual labels:  flask, celery
Flack
Companion code to my PyCon 2016 "Flask at Scale" tutorial session.
Stars: ✭ 458 (+465.43%)
Mutual labels:  flask, celery
Full Stack
Full stack, modern web application generator. Using Flask, PostgreSQL DB, Docker, Swagger, automatic HTTPS and more.
Stars: ✭ 451 (+456.79%)
Mutual labels:  flask, celery
Microsoftbotframework
Microsoft Bot Framework is a wrapper for the Microsoft Bot API by Microsoft
Stars: ✭ 68 (-16.05%)
Mutual labels:  flask, celery
Web develop
《Python Web开发实战》书中源码
Stars: ✭ 1,146 (+1314.81%)
Mutual labels:  flask, celery
Bugsnag Python
Official bugsnag error monitoring and error reporting for django, flask, tornado and other python apps.
Stars: ✭ 69 (-14.81%)
Mutual labels:  flask, celery
Kelime kok ayirici
Derin Öğrenme Tabanlı - seq2seq - Türkçe için kelime kökü bulma web uygulaması - Turkish Stemmer (tr_stemmer)
Stars: ✭ 76 (-6.17%)
Mutual labels:  flask
Poopak
POOPAK - TOR Hidden Service Crawler
Stars: ✭ 78 (-3.7%)
Mutual labels:  flask
Weixin Python
微信SDK - 包括微信支付,微信公众号,微信登陆,微信消息处理等
Stars: ✭ 1,191 (+1370.37%)
Mutual labels:  flask
Flask Graphql
Adds GraphQL support to your Flask application.
Stars: ✭ 1,188 (+1366.67%)
Mutual labels:  flask
Dfile
[Python + Flask] DFile: A fancy S3-based file sharing mode
Stars: ✭ 79 (-2.47%)
Mutual labels:  flask
Apps
Carson Sievert's web applications
Stars: ✭ 77 (-4.94%)
Mutual labels:  flask

Flask-Log-Request-Id

CircleCI

Flask-Log-Request-Id is an extension for Flask that can parse and handle the request-id sent by request processors like Amazon ELB, Heroku Request-ID or any multi-tier infrastructure as the one used at microservices. A common usage scenario is to inject the request_id in the logging system so that all log records, even those emitted by third party libraries, have attached the request_id that initiated their call. This can greatly improve tracing and debugging of problems.

Installation

The easiest way to install it is using pip from PyPI

pip install flask-log-request-id

Usage

Flask-Log-Request-Id provides the current_request_id() function which can be used at any time to get the request id of the initiated execution chain.

Example 1: Parse request id and print to stdout

from flask_log_request_id import RequestID, current_request_id

[...]

RequestID(app)


@app.route('/')
def hello():
    print('Current request id: {}'.format(current_request_id()))

Example 2: Parse request id and send it to to logging

In the following example, we will use the RequestIDLogFilter to inject the request id on all log events, and a custom formatter to print this information. If all these sounds unfamiliar please take a look at python's logging system

import logging
import logging.config
from random import randint
from flask import Flask
from flask_log_request_id import RequestID, RequestIDLogFilter

def 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 + b

app = Flask(__name__)
RequestID(app)

# Setup logging
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - level=%(levelname)s - request_id=%(request_id)s - %(message)s"))
handler.addFilter(RequestIDLogFilter())  # << Add request id contextual filter
logging.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))

The above will output the following log entries:

2017-07-25 16:15:25,912 - __main__ - level=INFO - request_id=7ff2946c-efe0-4c51-b337-fcdcdfe8397b - Adding two random numbers 11 14
2017-07-25 16:15:25,913 - __main__ - level=DEBUG - request_id=7ff2946c-efe0-4c51-b337-fcdcdfe8397b - Called generic_add(11, 14)
2017-07-25 16:15:25,913 - werkzeug - level=INFO - request_id=None - 127.0.0.1 - - [25/Jul/2017 16:15:25] "GET / HTTP/1.1" 200 -

Example 3: Forward request_id to celery tasks

Flask-Log-Request-Id comes with extras to forward the context of current request_id to the workers of celery tasks. In order to use this feature you need to enable the celery plugin and configure the Celery instance. Then you can use current_request_id() from inside your worker

from flask_log_request_id.extras.celery import enable_request_id_propagation
from flask_log_request_id import current_request_id
from celery.app import Celery
import logging

celery = Celery()
enable_request_id_propagation(celery)  # << This step here is critical to propagate request-id to workers

app = Flask()

@celery.task()
def generic_add(a, b):
    """Simple function to add two numbers that is not aware of the request id"""

    logging.debug('Called generic_add({}, {}) from request_id: {}'.format(a, b, current_request_id()))
    return a + b

@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.delay(a, b))  # Calling the task here, will forward the request id to the workers

You can follow the same logging strategy for both web application and workers using the RequestIDLogFilter as shown in example 1 and 2.

Example 4: If you want to return request id in response

This will be useful while integrating with frontend where in you can get the request id from the response (be it 400 or 500) and then trace the request in logs.

from flask_log_request_id import current_request_id

@app.after_request
def append_request_id(response):
    response.headers.add('X-REQUEST-ID', current_request_id())
    return response

Configuration

The following parameters can be configured through Flask's configuration system:

Configuration Name Description
LOG_REQUEST_ID_GENERATE_IF_NOT_FOUND In case the request does not hold any request id, the extension will generate one. Otherwise current_request_id will return None.
LOG_REQUEST_ID_LOG_ALL_REQUESTS If True, it will emit a log event at the request containing all the details as werkzeug would done along with the request_id .
LOG_REQUEST_ID_G_OBJECT_ATTRIBUTE This is the attribute of Flask.g object to store the current request id. Should be changed only if there is a problem. Use current_request_id() to fetch the current id.

License

See the LICENSE file for license rights and limitations (MIT).

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].