Skip to main content

fastapi gcp log formatting package

Project description

Fastapi_glogger

This is a package for formatting your fastapi logs into structured google logs to be used with google cloud services like cloud run.

Installation

Packge

Install the package using pip (only test package is available right now):

 pip install fastapi_glogger

Source Code

After cloning the repo

install dependencies using poetry

poetry install

Look the a main.py for a an example how to use it with FastAPI

from fastapi import FastAPI
from src.fastapi_glogger import setup_fastapi
import logging

app = setup_fastapi(FastAPI())


@app.get("/")
async def root():
    logging.info("Hello World")
    return {"message": "Hello World"}

Test mode (Locally)

To run the example code or package locally:

  • set the environment variable IS_TEST to true as it will need GOOGLE_APPLICATION_CREDENTIALS env variable otherwise to authenticate with google cloud logging.

On GCP (Cloud)

using cloud run you can deploy a container and the env variable gets set automatically from your account data.

API

setup_fastapi(app: FastAPI, additional_headers: Optional[Dict[str, str]] =None) -> FastAPI

  • app : the fast api constructor
  • additional_headers: dictionary where you specify:
    • key: the string you want injected the formatted log
    • value: the header that you want injected ex: {'testInject':'test'} it gets test from headers and puts it inside testInject in the outputted log

Examples

Additional Headers

Import and use the package in your Python script:

from fastapi import FastAPI
from fastapi_glogger import setup_fastapi
import logging

app =  setup_fastapi(FastAPI(), {"testInjected": "test"})

@app.get("/")
def read_root():
    logging.info("Hello world")
    return {"Hello world"}

The logged message should be outputted like this

{
    "severity": "INFO",
    "timestamp": "2024-09-05 09:48:01,485",
    "pathname": "/app/main.py",
    "logger_name": "root",
    "logging.googleapis.com/sourceLocation": {
        "file": "main.py",
        "line": "9",
        "function": "read_root"
    },
    "logging.googleapis.com/spanId": 9508110491393966220,
    "auditInfo": {
        "http_request": {
            "request_method": "GET",
            "request_url": "http://gcp-url/",
            "user_agent": "curl/7.36.1",
            "remote_ip": "52.12.45.123",
            "referer": null,
            "protocol": "https"
        },
        "testInjected": "This is test content"
    },
    "message": "[main:9]: Hello World"
}

Overriding exception handling

there is an existing wrapper over the fastapi exception handling for HTTPException and RequestValidationError that just adds a layer of logging above the fastapi handling. you can override these by adding your own exception handling code after setting up the formatter.

from fastapi import FastAPI
from fastapi_glogger import setup_fastapi
from fastapi.exceptions import RequestValidationError, HTTPException as StarletteHTTPException
import logging


app = setup_fastapi(FastAPI(), additional_headers={"TestInjected": "test"})

@app.add_exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
    logging.error(f"HTTP Exception: {exc.detail}")
    return exc


@app.get("/")
async def root():
    logging.info("Hello World")
    return {"message": "Hello World"}

License

MIT

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

fastapi_glogger-0.2.1.tar.gz (6.7 kB view details)

Uploaded Source

Built Distribution

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

fastapi_glogger-0.2.1-py3-none-any.whl (7.4 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_glogger-0.2.1.tar.gz.

File metadata

  • Download URL: fastapi_glogger-0.2.1.tar.gz
  • Upload date:
  • Size: 6.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/5.1.1 CPython/3.12.7

File hashes

Hashes for fastapi_glogger-0.2.1.tar.gz
Algorithm Hash digest
SHA256 e360e79ae38ced68fe3b91b45d720bc9ce8c9486326c2e3912ce8ca24c9acfba
MD5 8c9a2999cba95b17ea95daf4e512843a
BLAKE2b-256 f90ead58db9c6faa697a818a58c24e1f4f5b90734ee4c4b68ad30b7590ee836f

See more details on using hashes here.

File details

Details for the file fastapi_glogger-0.2.1-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_glogger-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b350902e4bb13f2a3d995096d2021677213a3b3278d2981392b80bf00a0829b4
MD5 012d7458d1859139ac3fbb6726a61a0b
BLAKE2b-256 e9fca030a96a298465faa2920c8fa969ce231014106ac438ad61cc63be8e32cb

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