Logging in FastAPI applications

Adding Logging Configuration for FastAPI Applications

Want more?

This lesson for enrolled students only. Join the course to unlock it!

You can see the code changes implemented in this lecture below.

If you have purchased the course in a different platform, you still have access to the code changes per lecture here on Teclado. The lecture video and lecture notes remain locked.
Join course for $30

New files

storeapi/logging_conf.py
from logging.config import dictConfig

from storeapi.config import DevConfig, config


def configure_logging() -> None:
    dictConfig(
        {
            "version": 1,
            "disable_existing_loggers": False,
            "formatters": {
                "console": {
                    "class": "logging.Formatter",
                    "datefmt": "%Y-%m-%dT%H:%M:%S",
                    "format": "%(name)s:%(lineno)d - %(message)s",
                },
            },
            "handlers": {
                "default": {
                    "class": "rich.logging.RichHandler",  # could use logging.StreamHandler instead
                    "level": "DEBUG",
                    "formatter": "console",
                },
            },
            "loggers": {
                "storeapi": {
                    "handlers": ["default"],
                    "level": "DEBUG" if isinstance(config, DevConfig) else "INFO",
                    "propagate": False,
                },
            },
        }
    )

Modified files

requirements.txt
--- 
+++ 
@@ -3,4 +3,5 @@
 uvicorn[standard]
 sqlalchemy
 databases[aiosqlite]
-python-dotenv+python-dotenv
+rich
storeapi/main.py
--- 
+++ 
@@ -3,11 +3,13 @@
 from fastapi import FastAPI

 from storeapi.database import database
+from storeapi.logging_conf import configure_logging
 from storeapi.routers.post import router as post_router


 @asynccontextmanager
 async def lifespan(app: FastAPI):
+    configure_logging()
     await database.connect()
     yield
     await database.disconnect()