Skip to content

Logging

Logging an application is a must and not a nice to have and mostly due to the errors that constantly happen during development time.


Table of Contents


InterceptHandler

As mentioned before, if not, please check API Settings, Python Web Extras uses FastAPI Utilities under the hood and therefore uses some of it's practices, more precisely the get_settings().

How to use it

To apply the interceptor, we recommend to add it into the base settings.

Example:

from loguru import logger
from python_web_extras.fastapi.api_settings import APISettings
from python_web_extras.fastapi.logging import InterceptHandler


class Settings(APISettings):
    ...
    ...


@lru_cache()
def get_settings() -> Settings:
    settings = Settings()
    configure_logger(settings)
    return settings


def configure_logger(settings: Settings) -> None:
    logging_level = logging.DEBUG if settings.debug else logging.INFO
    loggers = ("uvicorn.asgi", "uvicorn.access")
    logging.getLogger().handlers = [InterceptHandler()]
    for logger_name in loggers:
        logging_logger = logging.getLogger(logger_name)
        logging_logger.handlers = [InterceptHandler(level=logging_level)]

    logger.configure(handlers=[{"sink": sys.stderr, "level": logging_level}])

From now on when the app starts with these settings, it will have the InterceptHandler embed and operational.

Working example

An example of this approach can be found here.