The logging Module Basics
Configure loggers, set levels, and emit messages properly.
The logging Module Basics is a free Python Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why logging over print?
The logging module provides severity levels, configurable output destinations, timestamps, and the ability to silence output without code changes.
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("debug message")
logging.info("info message")
logging.warning("warning message")
logging.error("error message")
logging.critical("critical message")Log Levels
Python defines five standard levels in increasing severity: DEBUG, INFO, WARNING, ERROR, CRITICAL. Only messages at or above the configured level are emitted.
import logging
# Numeric values:
# DEBUG = 10
# INFO = 20
# WARNING = 30
# ERROR = 40
# CRITICAL = 50
logging.basicConfig(level=logging.WARNING)
logging.debug("hidden") # not shown
logging.warning("shown") # shownGetting a Logger
Use logging.getLogger(__name__) in every module. This creates a hierarchy matching the module structure.
import logging
logger = logging.getLogger(__name__)
def process(data):
logger.info("Processing %d items", len(data))
return [x * 2 for x in data]basicConfig Options
basicConfig quickly configures the root logger. Common kwargs: level, format, filename, filemode.
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(name)s — %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)Log Format Fields
Key format fields: %(levelname)s, %(name)s, %(message)s, %(asctime)s, %(filename)s, %(lineno)d.
import logging
fmt = "%(asctime)s | %(levelname)-8s | %(name)s:%(lineno)d | %(message)s"
logging.basicConfig(level=logging.DEBUG, format=fmt)
logging.info("Server started on port 8080")Logging Exceptions
Use logger.exception() inside an except block to log the message AND the full traceback.
import logging
logger = logging.getLogger(__name__)
try:
1 / 0
except ZeroDivisionError:
logger.exception("Division failed")
# Logs message + traceback automaticallyExtra Context with extra=
Pass a dict as extra= to add custom fields to the log record.
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(
format="%(asctime)s %(levelname)s [%(user)s] %(message)s"
)
logger.info("Login successful", extra={"user": "alice"})Lazy String Formatting
Pass format arguments separately — do not pre-format strings. This avoids the cost of string building when the message is filtered out.
import logging
logger = logging.getLogger(__name__)
# BAD (always builds the string):
logger.debug(f"Processing {len(data)} items")
# GOOD (only builds if DEBUG is enabled):
logger.debug("Processing %d items", len(data))Disabling Logging
Call logging.disable(level) to suppress all messages up to that level globally — useful in tests.
import logging
logging.disable(logging.CRITICAL) # suppress everything
# All log calls now silently do nothing
logging.disable(logging.NOTSET) # re-enableLogger Hierarchy
Logger names use dots as separators. Child loggers propagate to parent loggers unless propagate=False.
import logging
parent = logging.getLogger("myapp")
child = logging.getLogger("myapp.database")
# child propagates to parent by default
child.warning("DB slow") # also appears in myapp's handlersThe Root Logger
The root logger (from logging.warning() etc.) is the ancestor of all loggers. Configure it with basicConfig or by adding handlers directly.
import logging
root = logging.getLogger() # root logger
root.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
root.addHandler(handler)Quick Check
Which logging method should you use inside an except block to include the full traceback automatically?
Recap
Use named loggers with getLogger(__name__), configure via basicConfig, pass format arguments lazily, and use logger.exception() for error tracebacks. Loggers form a hierarchy rooted at the root logger.
Frequently asked questions
Is the “The logging Module Basics” lesson free?
Yes — the full text of “The logging Module Basics” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.
What will I learn in “The logging Module Basics”?
Configure loggers, set levels, and emit messages properly. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “The logging Module Basics” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The logging Module Basics
- Handlers, Formatters, and Filters
- Structured Logging
- Debugging with pdb