Logging is one of the most important tools for understanding what your application is doing. It helps you track down bugs, monitor performance, and keep an eye on how your app behaves in production. While it might be tempting to use print()
statements for quick debugging, logging is a much better approach for any real project. (Why not use print for logging?)
print()
is fine for quick tests, but it has serious limitations. Print statements don't include timestamps, log levels, or information about where the message came from. They also don't scale well - if you have a large application, finding the right print statement in a sea of output is a pain. Logging, on the other hand, is flexible and configurable. You can control what gets logged, where it goes, and how it looks. (The Twelve-Factor App: Logs)
Logging isn't just about dumping messages to the console. It's about recording the right information at the right time. Python's built-in logging
module uses log levels to help you control what gets logged and when: (Log Levels Explained)
By setting the log level, you decide how much detail you want to see.
Here's a simple way to set up logging for your FastAPI app. This approach uses Python's standard library and lets you control the log level through your configuration. (Structuring Python logs for production)
import logging import sys from app.config.main import get_settings settings = get_settings() def setup_logging(): """ Set up application-wide logging configuration. """ # Get the root logger logger = logging.getLogger() # Create formatter with the desired format formatter = logging.Formatter("[%(name)s - %(filename)s:%(lineno)d:%(funcName)s] %(levelname)s - %(message)s") # Create StreamHandler for console output and set the formatter handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) # Avoid duplicate handlers if setup_logging is called multiple times if not any(isinstance(h, logging.StreamHandler) for h in logger.handlers): logger.addHandler(handler) # Set the logging level from config logger.setLevel(getattr(logging, settings.LOGLEVEL.upper(), logging.INFO))
In the example above, and in my .env file, I have the setting LOGLEVEL=DEBUG
in my development environment. Want to know how to set up and manage configuration settings (like LOGLEVEL
) in your FastAPI app?
Check out my article: Centralizing Your FastAPI Configuration Settings with Pydantic Settings and .env Files.
In your main.py
(or wherever your FastAPI app starts), add:
from app.logging_config import setup_logging setup_logging()
This ensures that logging is set up before your app starts handling requests.
setup_logging()
is called more than once.INFO
or DEBUG
. (Log Levels Explained)Logging is a must-have for any FastAPI project. It's more powerful and flexible than print statements, and it helps you keep your app healthy and maintainable. Set it up early, use it consistently, and you'll thank yourself later.
Q: Can I log to a file instead of the console?
A: Yes. Replace StreamHandler(sys.stdout)
with FileHandler('your_log_file.log')
in your logging setup. (Python logging documentation)
Q: How do I change the log level?
A: Set the LOGLEVEL
in your configuration (like .env
or settings file) to DEBUG
, INFO
, WARNING
, etc.
Q: Can I add more context to my logs? A: Yes. You can customize the log format to include things like timestamps, process IDs, or request IDs.
Q: Is this setup enough for production? A: For many projects, yes. For larger apps, consider using structured logging, log rotation, or external log management services. (Structuring Python logs for production)
Q: Should I remove all print statements? A: Yes. Once you have logging set up, use it everywhere instead of print. Why not use print for logging?
David Muraya is a Solutions Architect specializing in Python, FastAPI, and Cloud Infrastructure. He is passionate about building scalable, production-ready applications and sharing his knowledge with the developer community. You can connect with him on LinkedIn.
Enjoyed this blog post? Check out these related posts!
Centralizing Your FastAPI Configuration Settings with Pydantic Settings
How to Organize and Load FastAPI Configuration Settings from a .env File Using Pydantic Settings
Read More..
Simple CI/CD for Your FastAPI App with Google Cloud Build and Cloud Run
Push code, deploy automatically: A simple CI/CD guide for your web app.
Read More..
Serving a React Frontend Application with FastAPI
A Guide to Serving Your Frontend and Backend from a Single Application
Read More..
Adding Google Authentication to Your FastAPI Application
A guide to adding Google Authentication to your FastAPI app.
Read More..
Have a project in mind? Send me an email at hello@davidmuraya.com and let's bring your ideas to life. I am always available for exciting discussions.