Logging in FastAPI applications

Adding JSON-formatted log files

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

requirements.txt
--- 
+++ 
@@ -5,4 +5,5 @@
 databases[aiosqlite]
 python-dotenv
 rich
-asgi-correlation-id+asgi-correlation-id
+python-json-logger
storeapi/logging_conf.py
--- 
+++ 
@@ -22,9 +22,11 @@
                     "format": "(%(correlation_id)s) %(name)s:%(lineno)d - %(message)s",
                 },
                 "file": {
-                    "class": "logging.Formatter",
+                    "class": "pythonjsonlogger.jsonlogger.JsonFormatter",
                     "datefmt": "%Y-%m-%dT%H:%M:%S",
-                    "format": "%(asctime)s.%(msecs)03dZ | %(levelname)-8s | [%(correlation_id)s] %(name)s:%(lineno)d - %(message)s",
+                    # For JsonFormatter, the format string just defines what keys are included in the log record
+                    # It's a bit clunky, but it's the way to do it for now
+                    "format": "%(asctime)s %(msecs)03d %(levelname)s %(correlation_id)s %(name)s %(lineno)d %(message)s",
                 },
             },
             "handlers": {