andreffs18 / flask-template-project

Empty template for a Flask 1.0 applications with some neat features!
MIT License
7 stars 2 forks source link

Add distributed logging tracing #19

Open andreffs18 opened 5 years ago

andreffs18 commented 5 years ago

On database operations, show stack trace:

try:
            Something
except Exception as e:
            logger.error(e, exc_info=True)
            db_session.rollback()
            return None

Setup logger custom format to show request id:

import logging

from flask import request, g

class CustomFormatter(logging.Formatter):

    def format(self, record):
        record.request_id = g.request_id
        record.correlation_id = g.correlation_id
        record.method = request.method
        record.path = request.path
        record.host = request.host
        return super(CustomFormatter, self).format(record)

Configure before and after request logging

import logging
from time import time
from uuid import uuid4

from flask import request, g, json

logger = logging.getLogger(__name__)

def setup_request_loggers(app):
    @app.before_request
    def log_request():
        g.start = time()
        g.request_id = request.headers.get('X-Request-Id') or uuid4()
        g.correlation_id = request.headers.get('X-Correlation-Id')
        values = request.get_json() or json.dumps(dict(request.form))
        logger.info("values={}".format(values))

def setup_response_loggers(app):
    @app.after_request
    def log_response(response):
        now = time()
        duration = round(now - g.start, 4)
        status_code = response.status_code
        logger.info("status={} duration {}s".format(status_code, duration))
        return response
andreffs18 commented 5 years ago

https://github.com/Workable/flask-log-request-id/tree/772903fdd1cd03074b7a0a7c362c42ace2cc03f9