Skip to main content

FastAPI middlewares to improve logging with stlog library

Project description

stlog-fastapi-middlewares

Python Badge UV Badge Mergify Badge Renovate Badge MIT Licensed

FastAPI/starlette middlewares to improve logging with stlog library.

Installation

pip install stlog-fastapi-middlewares

(or equivalent command for your favorite package manager)

Usage (with FastAPI)

import stlog
from fastapi import FastAPI
from fastapi.concurrency import asynccontextmanager
from stlog_fastapi_middlewares import (
    AccessLogMiddleware,
    CustomExceptionHandlingMiddleware,
    LogContextMiddleware,
)


@asynccontextmanager
async def lifespan(app: FastAPI):
    stlog.setup()
    yield


logger = stlog.getLogger(__name__)
app = FastAPI(lifespan=lifespan)
app.add_middleware(CustomExceptionHandlingMiddleware, logger=logger)
app.add_middleware(AccessLogMiddleware, logger=logger)
app.add_middleware(LogContextMiddleware, logger=logger)


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

Reference

We provide 3 independent middlewares.

CustomExceptionHandlingMiddleware

This middleware logs exceptions to structured logs.

No extra option is available.

Example:

import stlog
from fastapi import FastAPI
from fastapi.concurrency import asynccontextmanager
from stlog_fastapi_middlewares import (
    CustomExceptionHandlingMiddleware,
)


@asynccontextmanager
async def lifespan(app: FastAPI):
    stlog.setup()
    yield


logger = stlog.getLogger(__name__)
app = FastAPI(lifespan=lifespan)
app.add_middleware(CustomExceptionHandlingMiddleware, logger=logger)


@app.get("/exception")
async def exception():
    raise Exception("test")

AccessLogMiddleware

This middleware logs access to the application (to get access logs in JSON format for example).

You can optionally provide an ignore_hook option to ignore (for access log only!) some URLs.

Example:

import stlog
from fastapi import FastAPI
from fastapi.concurrency import asynccontextmanager
from stlog_fastapi_middlewares import (
    AccessLogMiddleware,
)


@asynccontextmanager
async def lifespan(app: FastAPI):
    stlog.setup()
    yield


logger = stlog.getLogger(__name__)
app = FastAPI(lifespan=lifespan)
app.add_middleware(AccessLogMiddleware, logger=logger)


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

[!NOTE] As FastAPI or uvicorn already outputs some access logs, you may want to disable them! For example, with uvicorn, you can use the --no-access-log flag.

LogContextMiddleware

This middleware adds some request context to structured logs (think of automatic request id, process id...).

There are multiple options to customize the middleware. See the corresponding code for reference.

Example:

import os
import stlog
from fastapi import FastAPI
from fastapi.concurrency import asynccontextmanager
from stlog_fastapi_middlewares import (
    LogContextMiddleware,
)


@asynccontextmanager
async def lifespan(app: FastAPI):
    stlog.setup()
    yield


logger = stlog.getLogger(__name__)
app = FastAPI(lifespan=lifespan)
app.add_middleware(
    LogContextMiddleware,
    logger=logger,
    add_pid=True,
    add_request_id=True,
    env_to_kvs={"FOO", "foo", "BAR", "bar"},
    headers_to_kvs={"X-Test-Id", "test_id"},
)

# Let's add some environment variables to test the middleware
os.environ["FOO"] = "foo2"
os.environ["BAR"] = "bar2"


@app.get("/")
async def root():
    logger.info("hello world")
    # => this call will output a log with the following extra keys:
    # - foo
    # - bar
    # - pid
    # - request_id
    # - test_id (if the call is made with a X-Test-Id header)
    return {"message": "Hello World"}

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

stlog_fastapi_middlewares-0.1.0.tar.gz (6.1 kB view details)

Uploaded Source

Built Distribution

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

stlog_fastapi_middlewares-0.1.0-py3-none-any.whl (6.7 kB view details)

Uploaded Python 3

File details

Details for the file stlog_fastapi_middlewares-0.1.0.tar.gz.

File metadata

File hashes

Hashes for stlog_fastapi_middlewares-0.1.0.tar.gz
Algorithm Hash digest
SHA256 d0423b56a0b1bc53638e6dba13699ba297232dfead7116ae4ae962c047138868
MD5 b9f6e038e143cec78de1799a2e3e47e0
BLAKE2b-256 1ec01b603d4a1c26626a587f347b405acacc11abb63b05bda811efe98c447aaa

See more details on using hashes here.

File details

Details for the file stlog_fastapi_middlewares-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for stlog_fastapi_middlewares-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8ae82583f56fe89362abd9f53cdcc6d6a52907c95f92c50ea5a784d98a9ef77f
MD5 02459d75877f3b018758feea1be1e003
BLAKE2b-256 1f173166bd84e2f847570b9df5dade57944ad45a9da76145216c45a41672fd7c

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