Logging in Python done simply
I constantly forget the right way to set up logging in Python without messing with other packages log levels. Here’s the snippet I always come back to:
# ./my_project_name/log.py
#
import logging
def setup_logging(level: int = logging.INFO) -> None:
logger = logging.getLogger("my_project_name") # TODO update this
logger.setLevel(level)
formatter = logging.Formatter("%(levelname)s:%(name)s:%(message)s")
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)- Uses a named logger (
"my_project_name"), not the root logger. - Sets only that logger’s level — other packages keep their own settings.
- Adds a single
StreamHandlerwith a clean format. - Call once at app start in
__init__.py:
# ./my_project_name/__init__.py
#
from my_project_name.log import setup_logging
setup_logging()Now logging.getLogger("my_project_name") anywhere in your project gives you a
ready‑to‑use logger that won’t interfere with anything else.
On top of this, we can also change the levels of other named loggers:
# ./my_project_name/log.py
#
import logging
def setup_logging(level: int = logging.INFO) -> None:
logger = logging.getLogger("my_project_name") # TODO update this
logger.setLevel(level)
formatter = logging.Formatter("%(levelname)s:%(name)s:%(message)s")
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
# Suppress urllib warning logs
#
# WARNING:urllib3.connectionpool:Connection pool is full, discarding connection: oauth2.googleapis.com. Connection pool size: 10
#
logging.getLogger("urllib3.connectionpool").setLevel(logging.ERROR)
# Suppress httpx info logs
#
# 2025-03-31 13:10:46 - httpx - INFO - HTTP Request: POST https://.../models/gemini-2.5-flash:generateContent "HTTP/1.1 429 Too Many Requests"
#
logging.getLogger("httpx").setLevel(logging.WARNING)#named-loggers #logging #customization #software-design #log-configuration #configuration #python #best-practices #maintainable-code #python-logging #programming #curated-collections
Reply to this post by email blZake@proZbableodyssey.blog (remove Z characters) ↪
Comments
Leave a comment
Markdown is supported. Your email is private and only used if you'd like a reply.