flake8-logging-format
flake8-logging-format is a Flake8 plugin designed to validate the format strings used in Python's standard `logging` calls. It helps prevent common errors like argument count mismatches or type mismatches between format specifiers and provided arguments. The current version is 2024.24.12, and it follows a calver-like release schedule based on active development.
Warnings
- gotcha This library is a plugin for Flake8. It will not work if Flake8 is not installed alongside it, or if it's installed in an environment where Flake8 is not active. Ensure both are installed in the same virtual environment.
- gotcha The default logging format regular expression (`log-format-expressions`) might not cover all custom logging practices. If you use unusual format specifiers or custom logging functions beyond standard Python `logging` or `printf`-style formatting, the plugin might produce false negatives (miss errors) or false positives (report non-existent errors).
Install
-
pip install flake8-logging-format
Imports
- Flake8 Plugin Availability
Install 'flake8-logging-format' and run 'flake8'.
Quickstart
import logging
# Configure a basic logger for demonstration
logging.basicConfig(level=logging.INFO)
def process_user(user_id, username):
logging.info("Processing user: %s (ID: %d)", username, user_id) # Correct usage
logging.warning("User with ID %s did something questionable", user_id) # LGA001: %s expects str, but user_id is int
logging.error("Failed operation on user %s", username, user_id) # LGA001: too many args (expected 1 for %s, got 2)
logging.info("Data: %s %s", "value1") # LGA001: too few args (expected 2 for %s %s, got 1)
# Example usage to trigger the logging calls (output is to console, but errors caught by flake8)
process_user(123, "john.doe")
# To run this with flake8-logging-format, save it as `main.py` and run:
# pip install flake8 flake8-logging-format
# flake8 main.py
#
# Expected output for `flake8 main.py`:
# main.py:8:5: LGA001 Format string argument count mismatch: '%s' for 'user_id' expects str, but got int.
# main.py:9:5: LGA001 Format string argument count mismatch: '%s' for 'username' expects 1 argument, but 2 were given.
# main.py:10:5: LGA001 Format string argument count mismatch: '%s %s' for 'value1' expects 2 arguments, but 1 was given.