🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreePython Logging Module: How to Log to Console and File

Runtime messages help show what a Python program is doing as it runs. Python’s built-in logging module records those events by severity and routes them to destinations such as the console or a file.
This article shows how to configure console and file output and use named loggers across modules.
TL;DR: Python Logging Module
Use Python’s built-in logging module to create records, set a severity threshold and send messages to a console or file.
- Choose logging.DEBUG, INFO, WARNING, ERROR or CRITICAL as the minimum level.
- Use logging.getLogger(__name__) in each module.
- Configure the root logger once near the application entry point.
What Is the Python Logging Module?
The logging module is part of Python’s standard library and records events while a program runs. A log record carries a message and its severity, then travels through a logger to one or more handlers.
A logger is the object application code calls. A handler routes records to a destination such as a stream or file, while a formatter decides which fields appear. A filter can accept or reject records based on rules beyond severity.
The five standard levels, from lower to higher severity, are DEBUG, INFO, WARNING, ERROR and CRITICAL. A configured threshold suppresses records below it. The default root threshold is WARNING, so a bare logging.info() call is normally silent.
The Python Logging HOWTO recommends named loggers for application code. A module-level logger named with __name__ follows the package hierarchy, which lets the application configure logging centrally.
How to Use the Python Logging Module Step by Step
Configure the application once, create a named logger in the code that reports events, and select the destination that should keep those records.
Step 1: Configure the root logger for a script
Call basicConfig() before the first logging call to set the threshold and format. In this example, INFO records and more severe records appear, while DEBUG records are filtered out.
import logging
logging.basicConfig(
level=logging.INFO,
format="%(levelname)s:%(name)s:%(message)s",
)
logger = logging.getLogger("checkout")
logger.debug("diagnostic detail")
logger.info("started")
In a fresh Python process, the output is:
INFO:checkout:started
The missing DEBUG line is expected because INFO is the threshold. In AskPython’s logging configuration guide, see how to extend the setup for more destinations and configuration needs.
Step 2: Create one named logger per module
In a reusable module, define a logger with logging.getLogger(__name__) and call its methods where events occur. The application entry point owns handlers and levels, so imported modules can participate without choosing where the application writes logs.
# inventory.py
import logging
logger = logging.getLogger(__name__)
def refresh_stock(count):
logger.info("stock refresh found %d items", count)
When the application configures the root logger, a record from inventory can propagate up the logger hierarchy to the root handler. This preserves one configuration point while each module identifies its source.
Step 3: Add a file destination
Set filename in basicConfig() to write to a file instead of the default console stream. The following program appends records to app.log and includes a timestamp, level and logger name.
import logging
logging.basicConfig(
filename="app.log",
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
logger = logging.getLogger(__name__)
logger.info("service started")
After the program exits, read app.log to inspect the record. The file handler appends by default. Choose filemode=”w” only when the old file should be replaced, and confirm that the process can write to the chosen directory.
Step 4: Include exception details
Call logger.exception() inside an exception handler to log the message and active traceback at ERROR level. Keep the exception context close to the operation that failed.
try:
quantity = int(raw_quantity)
except ValueError:
logger.exception("could not parse quantity")
In a fresh script with the INFO format above, I ran python3 logging_demo.py. The run printed the INFO record and an ERROR record followed by the ValueError traceback. The INFO threshold admits both levels, and logger.exception() preserves the failure context.

INFO:checkout:started order 27
ERROR:checkout:could not parse order status
Traceback (most recent call last):
File "/home/ubuntu/.cache/journaldev-article-runs/askpython-python-logging-module-20261116T054753Z-47a898d1dfed/logging_demo.py", line 8, in <module>
int("pending")
ValueError: invalid literal for int() with base 10: 'pending'
The traceback identifies the conversion and the invalid value. Avoid placing passwords, tokens or personal data in log messages because log files may be accessible to more people than the source code.
How logger objects route records
A logger creates a LogRecord when application code calls a severity method. Logger names form a dotted hierarchy: a logger named shop.payment is below shop, which is below the root logger. That naming structure lets an application adjust one package without changing unrelated modules.
A logger set to NOTSET does not impose its own threshold. Python looks upward for the first ancestor with a concrete level and uses that as the effective level. This is why a module logger can inherit the application’s INFO configuration.
After a record passes its originating logger’s level, propagation sends it to ancestor handlers unless propagation is disabled. Ancestor logger levels and filters are not reapplied to that propagated record, but each handler can still reject it. Setting propagate to false is useful when a logger has its own destination and should not duplicate output at the root.
How handler objects choose a destination
A handler receives records and sends them somewhere. StreamHandler writes to a stream such as the console, while FileHandler writes to a file. A rotating file handler can keep a bounded set of backups rather than allowing one log file to grow indefinitely.
Logger and handler thresholds are separate checks. For example, a logger may admit DEBUG records while a console handler set to WARNING displays only warnings and errors. A second file handler set to INFO can retain routine progress at the same time.
Attach handlers at the level where ownership is clear. An application usually configures destinations centrally, while a reusable library should create named loggers and leave handlers to the application. If both a child and its parent have handlers while propagation remains enabled, one record may be emitted twice.
A handler also has a formatter and can have filters, so each destination can present or select records differently. For example, a console can show concise warnings while a file keeps timestamped diagnostic detail. The logger still creates one record, and handlers independently decide what to do with it.
When troubleshooting, inspect the logger and handler objects rather than adding another handler immediately. Check the effective logger level, the handler level, the propagation setting and whether a handler is attached at more than one point in the hierarchy. This sequence distinguishes a suppressed record from a duplicate or misrouted one.
How formatter objects shape a record
A formatter turns a LogRecord into text. Its format string selects record attributes such as the timestamp, logger name, severity and message. That layout is separate from message arguments: passing a value as an argument to a logging call delays message interpolation until the record needs formatting.
formatter = logging.Formatter(
"%(asctime)s %(name)s %(levelname)s %(message)s",
datefmt="%H:%M:%S",
)
handler.setFormatter(formatter)
This layout adds a short clock time and keeps the source logger visible, which helps when several modules share a destination. The formatter style option can select percent, brace or dollar-style record layouts. It does not change how arguments in the logging call are interpolated.
How filter objects select records
Levels answer how severe a record is. Filters answer a different question, such as whether a particular subsystem or customer-facing event belongs in this destination. A filter can be attached to a logger or to a handler.
A logger filter applies to records handled by that logger itself. It does not automatically inspect every record created by descendant loggers during propagation. A handler filter instead sees records offered to that handler, making it a practical place to keep a destination-specific selection rule.
class CheckoutOnly(logging.Filter):
def filter(self, record):
return record.name.startswith("checkout")
handler.addFilter(CheckoutOnly())
With this filter, the handler accepts records from checkout loggers and rejects records from other names. Keep severity thresholds for severity and filters for contextual selection, so each rule has one clear job.
Logging Edge Cases and Fixes
Many missing messages come from a level threshold or existing handlers, rather than from a logger failing to create a record.
| Symptom | Cause | Fix |
|---|---|---|
| INFO messages do not appear | The default threshold is WARNING | Configure a lower level before logging |
| basicConfig changes have no effect | Root handlers already exist | Configure at process startup or deliberately use force=True when your application owns the reset |
| A named logger prints nothing | No suitable handler receives the record, or the logger/handler threshold filters it | Check both levels and the handler destination |
| Messages appear twice | A child logger has a handler and also propagates to a parent handler | Remove the duplicate handler or review propagate |
| File output fails | The path is invalid or not writable | Choose a writable path and check the operating-system permissions |
I ran python3 logging_failure.py with an unsupported level and got ValueError: Unknown level: ‘VERBOSE’. Use one of the standard constants such as logging.INFO, or define a custom level intentionally before configuring it.
A call to basicConfig() normally does nothing once the root logger has handlers. This commonly occurs in notebooks, interactive shells and frameworks. Python documents force=True as an option to replace existing root handlers, but it can disrupt a host application’s setup, so library code should not apply it automatically.
For selective output, use a handler on the relevant named logger or configure the hierarchy. Child records can propagate to ancestor handlers, where each handler applies its own threshold. Check both the logger’s effective level and the receiving handler’s level when a record is missing.
For more detailed routing, filters or several destinations, use explicit handlers or logging.config.dictConfig(). The Logging Cookbook covers multiple modules, while the AskPython exceptions guide reviews exception handling.
Conclusion
Use named loggers to report events and configure their destination at the application boundary. Set the threshold before the first message, then add a file handler or richer configuration only when the program needs it. Start with the official Logging HOWTO and logging reference for the full API.
FAQ
These answers cover the first questions that arise when configuring Python logging.
What is the Python logging module used for?
It records events from a running Python program with severity levels and routes them to configured destinations such as a console or file.
Why does logging.info() not show a message?
The root logger defaults to WARNING, which filters INFO. Configure a lower level before logging, such as logging.basicConfig(level=logging.INFO).
How do I use logging in multiple Python modules?
Define logging.getLogger(__name__) in each module and configure handlers and levels once in the application entry point. Child logger records can propagate to parent handlers.


