fastapi-and-logging


Namefastapi-and-logging JSON
Version 0.0.9 PyPI version JSON
download
home_pagehttps://github.com/heysaeid/fastapi-and-logging
SummaryFastAPI-and-Logging simplifies log handling, allowing for effective organization, tracking, and analysis of logs in FastAPI applications, aiding in debugging and issue resolut
upload_time2024-07-07 11:20:53
maintainerNone
docs_urlNone
authorSaeid Noormohammadi
requires_python<4.0,>=3.7
licenseMIT
keywords fastapi fastapi logging fastapi and logging
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # fastapi-and-logging
![FastAPI And Logging](https://raw.githubusercontent.com/heysaeid/fastapi-and-logging/main/docs/img/Color%20logo%20with%20background.svg)

[![Package version](https://img.shields.io/pypi/v/fastapi-and-logging?color=%2334D058&label=pypi%20package)](https://pypi.org/project/fastapi-and-logging/)
[![Downloads](https://img.shields.io/pypi/dm/fastapi-and-logging)](https://pypi.org/project/fastapi-and-logging/)
[![Supported Python versions](https://img.shields.io/pypi/pyversions/fastapi-and-logging.svg?color=%2334D058)](https://pypi.org/project/fastapi-and-logging/)
[![License](https://img.shields.io/badge/License-MIT-green.svg)](https://github.com/heysaeid/fastapi-and-logging/blob/master/LICENSE)

FastAPI-and-Logging simplifies log handling, allowing for effective organization, tracking, and analysis of logs in FastAPI applications, aiding in debugging and issue resolution.


Support for:
- Incoming Logger
- Exception Logger
- APICall Logger (HTTPX, AIOHttp, requests (coming soon...))
- Kafka (coming soon...)


# Install
```
pip install fastapi-and-logging
```


# Incomiong Logger

This `FastAPIIncomingLog` class is designed to log incoming system requests using FastAPI.

## Parameters:

- `app`: It is used to set route_class.
- `request_id_builder`: A function to build a request identifier, if specified(It uses uuid4 by default).
- `log_builder`: A function used to construct logs.
- `get_request_data`: A function used to retrieve request information.
- `get_response_data`: A function used to retrieve response information.
- `response_max_len`: The maximum length of a response stored in the log (default is 5000).
- `log_path (optional)`: Log file path.
- `log_type`: The type of logging, which can be one of various types (default is LogTypeEnum.FILE).

## How to Use:

To use this class, you can create an instance of it and set it as the `route_class` for your relevant Router in your FastAPI application.

```python
from fastapi import FastAPI
from fastapi_and_logging import FastAPIIncomingLog

app = FastAPI()
FastAPIIncomingLog(app)
```
# Customizing and Using Default Functions

The provided default functions (`get_request_data`, `get_response_data`, and `log_builder`) serve as customizable components for the `FastAPIIncomingLog` class. Here's how you can customize and use them:

## `get_request_data`

This function is responsible for extracting and formatting request data.

```python
from fastapi_and_logging import Request
from fastapi_and_logging.fastapi import get_request_data


async def customize_get_request_data(request: Request):
    # You can also use the output of the default function
    data = await get_request_data(request)
    return data
```

## `get_response_data`

This function handles the processing of response data.


```python
from fastapi import Response
from fastapi_and_logging.fastapi import get_response_data


def customize_get_response_data(response: Response) -> dict | str:
    # You can also use the output of the default function
    data = get_response_data(response)
    return data
```

## `log_builder`

The log_builder function constructs the log data based on various parameters.


```python
from fastapi import Request, Response
from user_agents.parsers import UserAgent
from fastapi_and_logging.fastapi import log_builder


def customize_log_builder(
    request: Request,
    response: Response,
    request_data: dict | str,
    response_data: dict | str,
    user_agent: UserAgent,
    start_time: int,
    end_time: int,
    duration: int,
):
    # You can also use the output of the default function
    data = log_builder(**)
    return data
```

# Exception Logger
To log all exceptions, simply use the ExceptionLogger class.

## Parameters:
- `app`: It is used to add exception handlers.
- `log_path (optional)`: Log file path.
- `log_type`: The type of logging, which can be one of various types (default is LogTypeEnum.FILE).
- `set_default_handlers`: Whether to set default exception handlers (default: True).

## How to Use:
```python
from fastapi import FastAPI
from fastapi_and_logging import ExceptionLogger

app = FastAPI()
ExceptionLogger(app)
```

You can also add your own exception handlers as follows:
```python
from fastapi import FastAPI, Request
from fastapi_and_logging import ExceptionLogger

app = FastAPI(debug=False)
exception_logger = ExceptionLogger(app=app)

async def test_exception_handler(request: Request, exc: Exception):
    return JSONResponse(
        content={"message": "Internal Server Error"},
    )

exception_logger.add_exception_handler(Exception, test_exception_handler)
```



# APICall Logger

**Note**: Currently it only supports httpx and aiohttp.

## HTTPXLogger
You can easily log all apicalls using httpx by adding the HTTPXLogger class.

### Parameters:

- `request_hook (optional)`: A callable object that serves as a hook for capturing and logging HTTP requests. It takes a single parameter, the request object, and does not return any value. Defaults to None..
- `response_hook (optional)`: A callable object that acts as a hook to capture and log HTTP responses. Any value returned will be logged.
- `sync_client (optional)`: A boolean value indicating whether the logging functionality should be applied to synchronous HTTP clients. If True, the hooks and configuration will be set for synchronous clients. Defaults to True.
- `async_client (optional)`: A boolean value indicating whether the logging functionality should be applied to asynchronous HTTP clients. If True, the hooks and configuration will be set for asynchronous clients. Defaults to True.
- `request_max_len (optional)`: An integer specifying the maximum length of the request body to be logged. If the request body exceeds this length, it will be truncated. Defaults to 5000 .
- `response_max_len (optional)`: An integer specifying the maximum length of the response body to be logged. If the response body exceeds this length, it will be truncated. Defaults to 5000.
- `log_path (optional)`: Log file path.
- `log_type (optional)`: Specifies the type of logging, currently it takes two values: console and file.

### How to Use:

```python
import httpx
from fastapi import FastAPI
from fastapi_and_logging.http_clients import HTTPXLogger


app = FastAPI()
HTTPXLogger()


@app.get("/")
def index():
    with httpx.Client() as client:
        response = client.get("http://localhost:8000/path")


# AsyncClient
@app.get("/")
async def index():
    async with httpx.AsyncClient() as client:
        response = await client.get("http://localhost:8000/path")
```


## AioHttpLogger
You can easily log all apicalls using httpx by adding the AioHttpLogger class.

### Parameters:

- `request_hook (optional)`: A callable object that serves as a hook for capturing and logging HTTP requests. It takes a single parameter, the request object, and does not return any value. Defaults to None..
- `response_hook (optional)`: A callable object that acts as a hook to capture and log HTTP responses. Any value returned will be logged.
- `request_max_len (optional)`: An integer specifying the maximum length of the request body to be logged. If the request body exceeds this length, it will be truncated. Defaults to 5000 .
- `response_max_len (optional)`: An integer specifying the maximum length of the response body to be logged. If the response body exceeds this length, it will be truncated. Defaults to 5000.
- `log_path (optional)`: Log file path.
- `log_type (optional)`: Specifies the type of logging, currently it takes two values: console and file.

### How to Use:

```python
import aiohttp
from fastapi import FastAPI
from fastapi_and_logging.http_clients import AioHttpLogger


app = FastAPI()
AioHttpLogger()


@app.get("/")
async def index():
    async with aiohttp.ClientSession() as session:
        async with session.get(
            "http://localhost:8000/path",
        ) as response:
            ...
```

To be able to have the request data or request ID associated with the incoming log in the apicall log, you need to follow the following steps. Additionally, you can send your desired parameters to log in the trace_request_ctx as well.
```python
import aiohttp
from fastapi import Request


@app.get("/")
async def index(request: Request):
    payload = {"name": "FastAPI And Logging"}
    async with aiohttp.ClientSession() as session:
        async with session.post(
            "http://localhost:8000/path",
            json = payload,
            trace_request_ctx = {
                "request_id": request.state.request_id,
                "request_data": payload,
            }
        ) as response:
            ...
```

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/heysaeid/fastapi-and-logging",
    "name": "fastapi-and-logging",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.7",
    "maintainer_email": null,
    "keywords": "fastapi, fastapi logging, fastapi and logging",
    "author": "Saeid Noormohammadi",
    "author_email": "heysaeid92@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/4f/86/e149acd322f343bc844a67fc30fbe262574e9f13bc68c4b73055d92c1f92/fastapi_and_logging-0.0.9.tar.gz",
    "platform": null,
    "description": "# fastapi-and-logging\n![FastAPI And Logging](https://raw.githubusercontent.com/heysaeid/fastapi-and-logging/main/docs/img/Color%20logo%20with%20background.svg)\n\n[![Package version](https://img.shields.io/pypi/v/fastapi-and-logging?color=%2334D058&label=pypi%20package)](https://pypi.org/project/fastapi-and-logging/)\n[![Downloads](https://img.shields.io/pypi/dm/fastapi-and-logging)](https://pypi.org/project/fastapi-and-logging/)\n[![Supported Python versions](https://img.shields.io/pypi/pyversions/fastapi-and-logging.svg?color=%2334D058)](https://pypi.org/project/fastapi-and-logging/)\n[![License](https://img.shields.io/badge/License-MIT-green.svg)](https://github.com/heysaeid/fastapi-and-logging/blob/master/LICENSE)\n\nFastAPI-and-Logging simplifies log handling, allowing for effective organization, tracking, and analysis of logs in FastAPI applications, aiding in debugging and issue resolution.\n\n\nSupport for:\n- Incoming Logger\n- Exception Logger\n- APICall Logger (HTTPX, AIOHttp, requests (coming soon...))\n- Kafka (coming soon...)\n\n\n# Install\n```\npip install fastapi-and-logging\n```\n\n\n# Incomiong Logger\n\nThis `FastAPIIncomingLog` class is designed to log incoming system requests using FastAPI.\n\n## Parameters:\n\n- `app`: It is used to set route_class.\n- `request_id_builder`: A function to build a request identifier, if specified(It uses uuid4 by default).\n- `log_builder`: A function used to construct logs.\n- `get_request_data`: A function used to retrieve request information.\n- `get_response_data`: A function used to retrieve response information.\n- `response_max_len`: The maximum length of a response stored in the log (default is 5000).\n- `log_path (optional)`: Log file path.\n- `log_type`: The type of logging, which can be one of various types (default is LogTypeEnum.FILE).\n\n## How to Use:\n\nTo use this class, you can create an instance of it and set it as the `route_class` for your relevant Router in your FastAPI application.\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_and_logging import FastAPIIncomingLog\n\napp = FastAPI()\nFastAPIIncomingLog(app)\n```\n# Customizing and Using Default Functions\n\nThe provided default functions (`get_request_data`, `get_response_data`, and `log_builder`) serve as customizable components for the `FastAPIIncomingLog` class. Here's how you can customize and use them:\n\n## `get_request_data`\n\nThis function is responsible for extracting and formatting request data.\n\n```python\nfrom fastapi_and_logging import Request\nfrom fastapi_and_logging.fastapi import get_request_data\n\n\nasync def customize_get_request_data(request: Request):\n    # You can also use the output of the default function\n    data = await get_request_data(request)\n    return data\n```\n\n## `get_response_data`\n\nThis function handles the processing of response data.\n\n\n```python\nfrom fastapi import Response\nfrom fastapi_and_logging.fastapi import get_response_data\n\n\ndef customize_get_response_data(response: Response) -> dict | str:\n    # You can also use the output of the default function\n    data = get_response_data(response)\n    return data\n```\n\n## `log_builder`\n\nThe log_builder function constructs the log data based on various parameters.\n\n\n```python\nfrom fastapi import Request, Response\nfrom user_agents.parsers import UserAgent\nfrom fastapi_and_logging.fastapi import log_builder\n\n\ndef customize_log_builder(\n    request: Request,\n    response: Response,\n    request_data: dict | str,\n    response_data: dict | str,\n    user_agent: UserAgent,\n    start_time: int,\n    end_time: int,\n    duration: int,\n):\n    # You can also use the output of the default function\n    data = log_builder(**)\n    return data\n```\n\n# Exception Logger\nTo log all exceptions, simply use the ExceptionLogger class.\n\n## Parameters:\n- `app`: It is used to add exception handlers.\n- `log_path (optional)`: Log file path.\n- `log_type`: The type of logging, which can be one of various types (default is LogTypeEnum.FILE).\n- `set_default_handlers`: Whether to set default exception handlers (default: True).\n\n## How to Use:\n```python\nfrom fastapi import FastAPI\nfrom fastapi_and_logging import ExceptionLogger\n\napp = FastAPI()\nExceptionLogger(app)\n```\n\nYou can also add your own exception handlers as follows:\n```python\nfrom fastapi import FastAPI, Request\nfrom fastapi_and_logging import ExceptionLogger\n\napp = FastAPI(debug=False)\nexception_logger = ExceptionLogger(app=app)\n\nasync def test_exception_handler(request: Request, exc: Exception):\n    return JSONResponse(\n        content={\"message\": \"Internal Server Error\"},\n    )\n\nexception_logger.add_exception_handler(Exception, test_exception_handler)\n```\n\n\n\n# APICall Logger\n\n**Note**: Currently it only supports httpx and aiohttp.\n\n## HTTPXLogger\nYou can easily log all apicalls using httpx by adding the HTTPXLogger class.\n\n### Parameters:\n\n- `request_hook (optional)`: A callable object that serves as a hook for capturing and logging HTTP requests. It takes a single parameter, the request object, and does not return any value. Defaults to None..\n- `response_hook (optional)`: A callable object that acts as a hook to capture and log HTTP responses. Any value returned will be logged.\n- `sync_client (optional)`: A boolean value indicating whether the logging functionality should be applied to synchronous HTTP clients. If True, the hooks and configuration will be set for synchronous clients. Defaults to True.\n- `async_client (optional)`: A boolean value indicating whether the logging functionality should be applied to asynchronous HTTP clients. If True, the hooks and configuration will be set for asynchronous clients. Defaults to True.\n- `request_max_len (optional)`: An integer specifying the maximum length of the request body to be logged. If the request body exceeds this length, it will be truncated. Defaults to 5000 .\n- `response_max_len (optional)`: An integer specifying the maximum length of the response body to be logged. If the response body exceeds this length, it will be truncated. Defaults to 5000.\n- `log_path (optional)`: Log file path.\n- `log_type (optional)`: Specifies the type of logging, currently it takes two values: console and file.\n\n### How to Use:\n\n```python\nimport httpx\nfrom fastapi import FastAPI\nfrom fastapi_and_logging.http_clients import HTTPXLogger\n\n\napp = FastAPI()\nHTTPXLogger()\n\n\n@app.get(\"/\")\ndef index():\n    with httpx.Client() as client:\n        response = client.get(\"http://localhost:8000/path\")\n\n\n# AsyncClient\n@app.get(\"/\")\nasync def index():\n    async with httpx.AsyncClient() as client:\n        response = await client.get(\"http://localhost:8000/path\")\n```\n\n\n## AioHttpLogger\nYou can easily log all apicalls using httpx by adding the AioHttpLogger class.\n\n### Parameters:\n\n- `request_hook (optional)`: A callable object that serves as a hook for capturing and logging HTTP requests. It takes a single parameter, the request object, and does not return any value. Defaults to None..\n- `response_hook (optional)`: A callable object that acts as a hook to capture and log HTTP responses. Any value returned will be logged.\n- `request_max_len (optional)`: An integer specifying the maximum length of the request body to be logged. If the request body exceeds this length, it will be truncated. Defaults to 5000 .\n- `response_max_len (optional)`: An integer specifying the maximum length of the response body to be logged. If the response body exceeds this length, it will be truncated. Defaults to 5000.\n- `log_path (optional)`: Log file path.\n- `log_type (optional)`: Specifies the type of logging, currently it takes two values: console and file.\n\n### How to Use:\n\n```python\nimport aiohttp\nfrom fastapi import FastAPI\nfrom fastapi_and_logging.http_clients import AioHttpLogger\n\n\napp = FastAPI()\nAioHttpLogger()\n\n\n@app.get(\"/\")\nasync def index():\n    async with aiohttp.ClientSession() as session:\n        async with session.get(\n            \"http://localhost:8000/path\",\n        ) as response:\n            ...\n```\n\nTo be able to have the request data or request ID associated with the incoming log in the apicall log, you need to follow the following steps. Additionally, you can send your desired parameters to log in the trace_request_ctx as well.\n```python\nimport aiohttp\nfrom fastapi import Request\n\n\n@app.get(\"/\")\nasync def index(request: Request):\n    payload = {\"name\": \"FastAPI And Logging\"}\n    async with aiohttp.ClientSession() as session:\n        async with session.post(\n            \"http://localhost:8000/path\",\n            json = payload,\n            trace_request_ctx = {\n                \"request_id\": request.state.request_id,\n                \"request_data\": payload,\n            }\n        ) as response:\n            ...\n```\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "FastAPI-and-Logging simplifies log handling, allowing for effective organization, tracking, and analysis of logs in FastAPI applications, aiding in debugging and issue resolut",
    "version": "0.0.9",
    "project_urls": {
        "Documentation": "https://github.com/heysaeid/fastapi-and-logging",
        "Homepage": "https://github.com/heysaeid/fastapi-and-logging",
        "Repository": "https://github.com/heysaeid/fastapi-and-logging"
    },
    "split_keywords": [
        "fastapi",
        " fastapi logging",
        " fastapi and logging"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b353d6dd0dbc4e7011915320e31c314f7973a2fbf962c6a9f6a1fd7f36ba4a89",
                "md5": "2ff236f7898b8fd49a4a309823f4b7c1",
                "sha256": "518cfad25b1cc99a2bd2807f8fde010d8173768b9bafa9f76d199e4f455510bd"
            },
            "downloads": -1,
            "filename": "fastapi_and_logging-0.0.9-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "2ff236f7898b8fd49a4a309823f4b7c1",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.7",
            "size": 11694,
            "upload_time": "2024-07-07T11:20:51",
            "upload_time_iso_8601": "2024-07-07T11:20:51.403298Z",
            "url": "https://files.pythonhosted.org/packages/b3/53/d6dd0dbc4e7011915320e31c314f7973a2fbf962c6a9f6a1fd7f36ba4a89/fastapi_and_logging-0.0.9-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4f86e149acd322f343bc844a67fc30fbe262574e9f13bc68c4b73055d92c1f92",
                "md5": "fd33d1580c0b4be4e332b0a964ffe94e",
                "sha256": "363723686b9bbf6267e89a906a7e6f6b10f291f20d709c34027014a950f216aa"
            },
            "downloads": -1,
            "filename": "fastapi_and_logging-0.0.9.tar.gz",
            "has_sig": false,
            "md5_digest": "fd33d1580c0b4be4e332b0a964ffe94e",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.7",
            "size": 10699,
            "upload_time": "2024-07-07T11:20:53",
            "upload_time_iso_8601": "2024-07-07T11:20:53.146749Z",
            "url": "https://files.pythonhosted.org/packages/4f/86/e149acd322f343bc844a67fc30fbe262574e9f13bc68c4b73055d92c1f92/fastapi_and_logging-0.0.9.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-07-07 11:20:53",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "heysaeid",
    "github_project": "fastapi-and-logging",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "fastapi-and-logging"
}
        
Elapsed time: 0.30811s