-
Notifications
You must be signed in to change notification settings - Fork 250
Description
I am currently working on integrating Structlog as the default logger for the FastAPI boilerplate and would like to get feedback from the community.
A reference implementation is already available here: https://github.com/sri-dhurkesh/FastAPI-boilerplate/tree/feature/structured-logging — please refer to logger.py, logger_middleware.py, and config.py for the full setup.
The main goal of this migration is to improve log structure, flexibility, and customization, while keeping the logging setup simple and practical for both development and production environments.
Proposed Approach
I am planning to configure two separate log handlers, each with its own settings:
- Console (stdout) logger – mainly for local development and debugging.
- File logger (
app.log) – primarily for production usage with better structure and persistence.
Each handler can be configured independently to use either JSON-formatted logs or plain text logs, depending on the environment and requirements.
Example Configuration
# config.py
class FileLoggerSettings(BaseSettings):
FILE_LOG_MAX_BYTES: int = 10 * 1024 * 1024
FILE_LOG_BACKUP_COUNT: int = 5
FILE_LOG_FORMAT_JSON: bool = True
FILE_LOG_LEVEL: str = "INFO"
# Include request ID, path, method, client host, and status code in the file log
FILE_LOG_INCLUDE_REQUEST_ID: bool = True
FILE_LOG_INCLUDE_PATH: bool = True
FILE_LOG_INCLUDE_METHOD: bool = True
FILE_LOG_INCLUDE_CLIENT_HOST: bool = True
FILE_LOG_INCLUDE_STATUS_CODE: bool = True
class ConsoleLoggerSettings(BaseSettings):
CONSOLE_LOG_LEVEL: str = "INFO"
CONSOLE_LOG_FORMAT_JSON: bool = False
# Include request ID, path, method, client host, and status code in the console log
CONSOLE_LOG_INCLUDE_REQUEST_ID: bool = False
CONSOLE_LOG_INCLUDE_PATH: bool = False
CONSOLE_LOG_INCLUDE_METHOD: bool = False
CONSOLE_LOG_INCLUDE_CLIENT_HOST: bool = False
CONSOLE_LOG_INCLUDE_STATUS_CODE: bool = FalseWhat This Enables
-
Configurable log format
I can choose JSON or human-readable text separately for log files and stdout. -
Easy usage across environments
The same setup works well for both development and production, driven entirely by configuration. -
Better customization
I get fine-grained control over what context (request ID, path, method, status code, etc.) is included in each log handler. -
Improved observability
Structured JSON logs make it easier to integrate with log aggregation and monitoring tools.
I’d like to know if the community is open to migrating from the basic logger to Structlog and whether this approach aligns with your expectations or use cases.