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.5.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.5-py3-none-any.whl (4.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: nero-fastapi-logger-lib-0.1.5.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.5.tar.gz
Algorithm Hash digest
SHA256 1a041efdbef62fabf29d070d3e639a5aaf7be174196217547d03f3e7d1eaefc5
MD5 9031efca3be52cc1cfbd394cc8f70244
BLAKE2b-256 fc7d644b5dcf60da7c083688d82efcd12459c9700e16d473421ce599f2092b80

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for nero_fastapi_logger_lib-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 0fc228bc9af95462aebefc09ab5c0299b11b7270e3e8b8c6afc39c110e51497f
MD5 de21724aa7691b76ba69e4598ae144c2
BLAKE2b-256 51d3be0d031b7047290be28ab75c3b36309e5fb0bfe773a538bcdbed0fc78160

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