Setting Up Multiple Loggers in the Logging Module

In larger FastAPI applications, it can be beneficial to create multiple loggers to organize and manage log messages more effectively. This allows you to log different types of information to separate destinations or with different levels of detail.

Creating Multiple Loggers

Create a Logging Module:

Python

import logging

def get_logger(name):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)

# Create a handler and formatter
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

logger.addHandler(handler)
return logger

Use the Logging Module in Your Application:

Python

from app.logging import get_logger

logger = get_logger(name)

@app.get(“/”)
def read_root():
logger.info(“Received a GET request to /”)
return {“Hello”: “World”}

Creating Separate Loggers for Different Modules

To create separate loggers for different modules, use unique names when calling get_logger:

Python

# In module1.py
logger1 = get_logger("app.module1")

# In module2.py
logger2 = get_logger("app.module2")

Controlling Logging Levels

You can set different logging levels for each logger to control which messages are logged:

Python

logger1.setLevel(logging.DEBUG)
logger2.setLevel(logging.INFO)

Using Logger Hierarchies

Logger hierarchies allow you to control logging for entire groups of modules. For example, if you have a logger named app.module1, all loggers with names starting with app.module1 will inherit its logging level.

Adding File Handlers for Log Storage
Configuring Logging for FastAPI Apps

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?