Logging in FastAPI applications

Logging HTTPExceptions with an Exception Handler

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

Modified files

storeapi/main.py
--- 
+++ 
@@ -1,11 +1,13 @@
+import logging
 from contextlib import asynccontextmanager

-from fastapi import FastAPI
-
+from fastapi import FastAPI, HTTPException
+from fastapi.exception_handlers import http_exception_handler
 from storeapi.database import database
 from storeapi.logging_conf import configure_logging
 from storeapi.routers.post import router as post_router

+logger = logging.getLogger(__name__)

 @asynccontextmanager
 async def lifespan(app: FastAPI):
@@ -18,3 +20,11 @@


 app.include_router(post_router)
+
+
+@app.exception_handler(HTTPException)
+async def http_exception_handle_logging(request, exc):
+    logger.error(f"HTTPException: {exc.status_code} {exc.detail}")
+    return await http_exception_handler(request, exc)
+
+
storeapi/routers/post.py
--- 
+++ 
@@ -56,7 +56,6 @@
     post = await find_post(comment.post_id)

     if not post:
-        logger.error(f"Post with id {comment.post_id} not found")
         raise HTTPException(status_code=404, detail="Post not found")

     data = comment.model_dump()  # previously .dict()
@@ -86,7 +85,6 @@
     post = await find_post(post_id)

     if not post:
-        logger.error(f"Post with post id {post_id} not found")
         raise HTTPException(status_code=404, detail="Post not found")

     return {