HomeBlog

Setting Up Logging in FastAPI: A Practical Guide

3 min read
Illustration of FastAPI application generating structured logs with log levels and cloud logging integration
By David Muraya • August 16, 2025

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?)

Why Not Just Use Print?

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)

Understanding Log Levels

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)

  • CRITICAL: Very serious errors that may cause the program to stop.
  • ERROR: Problems that prevent a function or request from completing properly.
  • WARNING: Something unexpected happened, but the app can continue.
  • INFO: General events that confirm the application is working as expected.
  • DEBUG: Detailed information useful during development and troubleshooting.

By setting the log level, you decide how much detail you want to see.

How I Set Up Logging in FastAPI

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.

What This Setup Gives You

  • Consistent formatting: Every log message includes the logger name, filename, line number, and function name.
  • Configurable log level: You can control how much detail you see by changing a single setting.
  • No duplicate logs: The check for existing handlers prevents repeated log messages if setup_logging() is called more than once.

Tips for Using Logging Effectively

  • Use the right log level for each message. Don't log everything as INFO or DEBUG. (Log Levels Explained)
  • Avoid logging sensitive information. (OWASP Logging Cheat Sheet)
  • In production, consider sending logs to a file or a logging service instead of just the console. In environments like Google Cloud Run, your logs will automatically appear under Monitoring > Logs Explorer (formerly Stackdriver). This makes it easy to search, filter, and analyze logs from your FastAPI app alongside other Google Cloud resources.
  • Review your logs regularly - they're only useful if you look at them.

Conclusion

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.


FAQ

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?

About the Author

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.

Related Blog Posts

Enjoyed this blog post? Check out these related posts!

Centralizing Your FastAPI Configuration Settings with Pydantic Settings

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

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

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

Adding Google Authentication to Your FastAPI Application

A guide to adding Google Authentication to your FastAPI app.

Read More..

Contact Me

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.

© 2025 David Muraya. All rights reserved.