Skip to main content

A logging library for FastAPI with request_id tracking

Project description

FastAPI Logger Library

This is a reusable logging library for FastAPI applications with request_id tracking.

Installation

pip install nero-fastapi-logger-lib

Usage

from fastapi_logger.logger import logger

logger.info("Hello from FastAPI!")

want to setup with sqlalchemy logger

from fastapi_logger.logger import logger, setup_sqlalchemy_logging
setup_sqlalchemy_logging()
logger.info("Hello from FastAPI!")

example dbConnector for this sqlalchemy log

from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker

from src.configs.env import Env

class DBManager:
    _engine = create_engine(
                Env.DATABASE_URL,
                pool_size=10,
                max_overflow=0,
                pool_timeout=30,
                pool_recycle=3600,
                pool_pre_ping=True
            )
    _Session = sessionmaker(bind=_engine)

    @classmethod
    def get_engine(cls):
        if cls._engine is None:
            raise Exception("Engine not initialized. Call initialize() first.")
        return cls._engine

    @classmethod
    def get_session(cls):
        if cls._Session is None:
            raise Exception("Engine not initialized. Call initialize() first.")
        return cls._Session()

    @classmethod
    def execute_raw_sql(cls, query, params=None, result_model=None):
        if cls._engine is None:
            raise Exception("Engine not initialized. Call initialize() first.")
        with cls._engine.connect() as connection:
            result = connection.execute(text(query), params)
            if result_model:
                # Map the result to the data class
                mapped_result = [result_model(**row) for row in result.mappings()]
                return mapped_result
            return result.fetchall()

to setup with each request

class RequestIDMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        request_id = generate_api_request_id()  # Set API request_id at start
        response = await call_next(request)
        response.headers['X-Request-ID'] = request_id
        clear_api_request_id()  # Clear API request_id after response
        return response

class LoggingMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        # Log the start of the request
        logger.info(f"Started {request.method} {request.url}")

        # Continue handling the request
        response = await call_next(request)

        # Log the end of the request
        logger.info(f"Completed {request.method} {request.url} with status code {response.status_code}")

        return response

app = FastAPI()
app.add_middleware(LoggingMiddleware)
app.add_middleware(RequestIDMiddleware)

Features

  • Request ID tracking for API & Cron jobs
  • JSON & color log formatting
  • Compatible with FastAPI middleware

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nero-fastapi-logger-lib-0.1.6.tar.gz (4.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

nero_fastapi_logger_lib-0.1.6-py3-none-any.whl (5.0 kB view details)

Uploaded Python 3

File details

Details for the file nero-fastapi-logger-lib-0.1.6.tar.gz.

File metadata

  • Download URL: nero-fastapi-logger-lib-0.1.6.tar.gz
  • Upload date:
  • Size: 4.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.16

File hashes

Hashes for nero-fastapi-logger-lib-0.1.6.tar.gz
Algorithm Hash digest
SHA256 d09878ef633a15a60b88d9a8f67a11ee4fba14b9174b6ff94eb1bf8ab9d68e40
MD5 77c14385d133bf644772b6703b88165b
BLAKE2b-256 c5a3a288c748f2cb7aa3842a3be1ba46fac93df1817226bbe6fce79d336b50bb

See more details on using hashes here.

File details

Details for the file nero_fastapi_logger_lib-0.1.6-py3-none-any.whl.

File metadata

File hashes

Hashes for nero_fastapi_logger_lib-0.1.6-py3-none-any.whl
Algorithm Hash digest
SHA256 e82a6b618799a92357fa626768c287a0b3d07abea2221132667364d3f15b3d80
MD5 47c432e1671ef822c974a198a14ac49c
BLAKE2b-256 9484b94506f398cbdbae8956e944df9c73685923d44e4bfa0c4dcf686ff66fb0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page