Logging in FastAPI applications

Adding Logtail for Cloud Logging in FastAPI

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
--- 
+++ 
@@ -6,4 +6,5 @@
 python-dotenv
 rich
 asgi-correlation-id
-python-json-logger+python-json-logger
+logtail-python
storeapi/config.py
--- 
+++ 
@@ -17,6 +17,7 @@
 class GlobalConfig(BaseConfig):
     DATABASE_URL: Optional[str] = None
     DB_FORCE_ROLL_BACK: bool = False
+    LOGTAIL_API_KEY: Optional[str] = None


 class DevConfig(GlobalConfig):
storeapi/logging_conf.py
--- 
+++ 
@@ -59,6 +59,14 @@
                     "formatter": "console",
                     "filters": ["correlation_id", "email_obfuscation"],
                 },
+                "logtail": {
+                    # https://betterstack.com/docs/logs/python/
+                    "class": "logtail.LogtailHandler",
+                    "level": "DEBUG",
+                    "formatter": "console",
+                    "filters": ["correlation_id", "email_obfuscation"],
+                    "source_token": config.LOGTAIL_API_KEY,  # gets passed to LogtailHandler constructor as kwargs
+                },
                 "rotating_file": {
                     "class": "logging.handlers.RotatingFileHandler",
                     "level": "DEBUG",
@@ -73,7 +81,7 @@
             "loggers": {
                 "uvicorn": {"handlers": ["default", "rotating_file"], "level": "INFO"},
                 "storeapi": {
-                    "handlers": ["default", "rotating_file"],
+                    "handlers": ["default", "rotating_file", "logtail"],
                     "level": "DEBUG" if isinstance(config, DevConfig) else "INFO",
                     "propagate": False,
                 },