Python logging provides a standard way to record what an application is doing while it runs. Logging is useful for debugging failures, understanding application behavior, tracking important business operations, and diagnosing production problems without stopping the application or manually inspecting its source code.
Python's built-in
logging
module is designed to support different levels of messages, reusable loggers, multiple output destinations, custom formats, exception information, and centralized configuration.
Unlike temporary
print()
statements, logging gives an application a consistent mechanism for deciding what information should be recorded and where it should go.
Good logging is not about writing as many messages as possible. It is about recording the right information at the right level, in a way that helps developers and operators understand what happened.
What You Will Learn
- Why logging is important in Python applications
- How loggers, handlers, formatters, and levels work
- How to use DEBUG, INFO, WARNING, ERROR, and CRITICAL
- How to configure logging with basicConfig()
- How to write logs to files
- How to include exception information
- How logger hierarchy and propagation work
- How to create reusable module-level loggers
- How to add useful context such as request or job identifiers
- How to design logging for production systems
Why Use Logging?
A small script can often use
print()
for temporary output. A real application, however, usually needs more control.
For example, a web API may need to distinguish between normal requests, suspicious input, validation failures, database errors, and unexpected application failures. Logging allows each event to be classified and routed appropriately.
import logging
logging.basicConfig(
level=logging.INFO
)
logging.info(
"Application started"
)
logging.warning(
"Configuration value is missing"
)
logging.error(
"Database operation failed"
)
Logging also becomes valuable after deployment, where direct debugging may not be available. Logs can provide a timeline of events that helps identify what happened before a failure.
The Python Logging Model
The logging system can be understood through four main concepts:
| Component | Purpose |
|---|---|
| Logger | Creates and categorizes log records |
| Handler | Determines where records are sent |
| Formatter | Controls how log records are displayed |
| Level | Controls which messages are considered important enough to process |
Log Levels
Python provides standard logging levels that communicate the importance or severity of an event.
| Level | Typical Meaning | Example |
|---|---|---|
DEBUG |
Detailed diagnostic information | Entering a function with internal state |
INFO |
Normal application events | Order successfully created |
WARNING |
Unexpected situation that may require attention | Retrying an external request |
ERROR |
An operation failed | Database query failed |
CRITICAL |
Severe failure that may prevent continued operation | Required infrastructure is unavailable |
DEBUG Logging
DEBUG is intended for detailed diagnostic information that is usually too noisy for normal production operation.
import logging
logger = logging.getLogger(__name__)
def calculate_total(
price,
quantity
):
logger.debug(
"Calculating total: price=%s quantity=%s",
price,
quantity
)
return price * quantity
INFO Logging
INFO is appropriate for meaningful normal application events. These messages should help someone understand the general behavior of the application without producing excessive noise.
logger.info(
"Order %s created successfully",
order_id
)
WARNING Logging
WARNING indicates something unusual happened, but the application can continue. It can be useful for fallback behavior, deprecated configuration, retry attempts, or unexpected but recoverable states.
logger.warning(
"Payment service response was slow: %s ms",
elapsed_ms
)
ERROR Logging
ERROR indicates that an operation failed. The application may continue running, but the particular operation could not complete successfully.
try:
save_order(order)
except DatabaseError:
logger.error(
"Failed to save order %s",
order_id
)
CRITICAL Logging
CRITICAL should be reserved for severe conditions where normal application operation may no longer be possible.
logger.critical(
"Application cannot start because required configuration is unavailable"
)
Creating a Logger
In reusable modules, a common pattern is to create a module-level logger using
logging.getLogger(__name__).
This gives the logger a name corresponding to the module and allows applications to configure related loggers through the logger hierarchy.
import logging
logger = logging.getLogger(__name__)
def process_user(user_id):
logger.info(
"Processing user %s",
user_id
)
This is generally preferable to configuring the global logging system independently inside every module.
basicConfig()
For small scripts and straightforward applications,
logging.basicConfig()
provides a convenient way to configure basic logging behavior.
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(message)s"
)
logger = logging.getLogger(__name__)
logger.info(
"Application started"
)
Once a more complex application has multiple output destinations, different formatting requirements, or centralized configuration, explicit handlers and formatters provide more control.
Log Formatters
A formatter determines how a log record is represented. Useful fields include timestamps, level names, logger names, module information, and the actual message.
import logging
logging.basicConfig(
level=logging.INFO,
format=(
"%(asctime)s | "
"%(levelname)s | "
"%(name)s | "
"%(message)s"
)
)
logger = logging.getLogger(__name__)
logger.info(
"User login completed"
)
Important Formatting Fields
| Field | Meaning |
|---|---|
%(asctime)s |
Timestamp of the log record |
%(levelname)s |
Log severity |
%(name)s |
Logger name |
%(message)s |
Formatted log message |
%(filename)s |
Source filename associated with the record |
Handlers
A handler decides where a log record is sent. An application can use different handlers for different destinations.
Common destinations include the console, files, rotating files, or custom streams used by an application's deployment environment.
import logging
logger = logging.getLogger(
"application"
)
console_handler = logging.StreamHandler()
logger.addHandler(
console_handler
)
logger.setLevel(
logging.INFO
)
logger.info(
"Message sent to console"
)
File Logging
File logging is useful for applications where log records need to be persisted locally. The
FileHandler
can write logging records to a file.
import logging
logging.basicConfig(
filename="application.log",
level=logging.INFO,
format=(
"%(asctime)s | "
"%(levelname)s | "
"%(message)s"
)
)
logging.info(
"Application started"
)
In containerized and cloud environments, applications often prefer writing logs to standard output or standard error and letting the platform collect them. The important principle is to choose a destination that matches the deployment architecture.
Rotating Log Files
Writing to one file indefinitely can cause the log file to grow without limit. Python provides rotating handlers that can create new files when size or time thresholds are reached.
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger(
"application"
)
logger.setLevel(
logging.INFO
)
handler = RotatingFileHandler(
"application.log",
maxBytes=1_000_000,
backupCount=3
)
logger.addHandler(handler)
logger.info(
"Rotating file logging enabled"
)
Time-Based Rotation
Time-based rotation can be useful when logs should be separated by periods such as days or hours.
from logging.handlers import TimedRotatingFileHandler
handler = TimedRotatingFileHandler(
"application.log",
when="midnight",
backupCount=7
)
Choose retention and rotation policies based on operational requirements rather than keeping every log forever by default.
Exception Logging
When an operation fails because of an exception, logging the exception details can dramatically improve debugging. The
logger.exception()
method is especially useful inside an exception handler because it includes the current exception traceback.
try:
result = process_payment()
except PaymentError:
logger.exception(
"Payment processing failed"
)
Use exception logging when the traceback provides useful diagnostic information. Avoid logging the same exception repeatedly at every layer unless each log adds genuinely useful context.
logger.exception() vs logger.error()
try:
operation()
except Exception:
logger.exception(
"Operation failed"
)
The example above records the traceback. An
error()
call records an error-level message, but does not automatically include the current traceback unless exception information is explicitly supplied.
Exception Information with exc_info
Exception information can also be included explicitly when needed.
try:
risky_operation()
except Exception:
logger.error(
"Risky operation failed",
exc_info=True
)
Use Lazy Logging Arguments
Prefer the logging module's formatting arguments instead of constructing strings with f-strings before every logging call.
# Preferred
logger.info(
"User %s logged in",
user_id
)
# Less suitable for logging calls
logger.info(
f"User {user_id} logged in"
)
Passing values separately allows the logging system to decide whether the message needs to be formatted based on the active log level.
Logger Hierarchy
Logger names form a hierarchy separated by periods. For example,
app,
app.users,
and
app.users.service
can represent different parts of the same application.
app
├── app.users
│ ├── app.users.service
│ └── app.users.repository
└── app.orders
├── app.orders.service
└── app.orders.repository
This hierarchy allows application-level configuration to affect groups of related loggers.
Propagation
Log records generated by child loggers can propagate to ancestor loggers. This is useful when handlers are configured centrally, but it can also cause duplicate messages when the same record is handled by multiple handlers.
When diagnosing duplicate logs, inspect both the handlers attached to the logger and its propagation behavior.
Do Not Configure Logging in Every Module
A common application design is to let the application entry point configure logging while individual modules simply obtain their logger and emit records.
# app.py
import logging
logging.basicConfig(
level=logging.INFO,
format=(
"%(asctime)s | "
"%(levelname)s | "
"%(name)s | "
"%(message)s"
)
)
from users import create_user
create_user("Alex")
# users.py
import logging
logger = logging.getLogger(__name__)
def create_user(name):
logger.info(
"Creating user %s",
name
)
Log Useful Context
A message such as
"Request failed"
is rarely enough to diagnose a production problem. Useful context might include a request ID, user ID, job ID, operation name, duration, or external service name.
logger.info(
"Processing order_id=%s user_id=%s",
order_id,
user_id
)
The context should help someone locate and understand the event without forcing the log system to expose unnecessary application data.
Using extra Context
The logging API supports additional contextual fields through
extra.
This can be useful when a logging formatter expects custom fields.
import logging
formatter = logging.Formatter(
"%(asctime)s | "
"%(levelname)s | "
"request=%(request_id)s | "
"%(message)s"
)
handler = logging.StreamHandler()
handler.setFormatter(
formatter
)
logger = logging.getLogger(
"application"
)
logger.setLevel(
logging.INFO
)
logger.addHandler(handler)
logger.info(
"Request started",
extra={
"request_id": "req-123"
}
)
LoggerAdapter
When the same contextual information should be added to many messages, a
LoggerAdapter
can reduce repetition.
import logging
logger = logging.getLogger(
"application"
)
logger = logging.LoggerAdapter(
logger,
{
"request_id": "req-123"
}
)
logger.info(
"Starting request"
)
logger.info(
"Loading user profile"
)
This approach is especially useful when logs need consistent request-level or job-level context.
Do Not Log Sensitive Information
Logs can be retained, copied, shipped to third-party systems, and accessed by operational tooling. Passwords, authentication tokens, private keys, payment secrets, and other sensitive values should not be casually written to logs.
# Avoid
logger.info(
"Login password=%s",
password
)
# Better
logger.info(
"Login attempt for user=%s",
username
)
Avoid Logging Everything
Excessive logging can make important events harder to find. A production system with thousands of repetitive messages per second can become difficult to search and expensive to store.
A useful log message should answer one or more of these questions:
- What happened?
- Which operation or resource was involved?
- Why is this event useful for diagnosis?
- What information is needed to continue debugging?
Logging Performance
Logging has a cost. Formatting messages, writing to streams, and shipping records to centralized systems all consume resources.
Avoid constructing expensive diagnostic values when DEBUG logging is disabled.
if logger.isEnabledFor(logging.DEBUG):
expensive_details = build_debug_details()
logger.debug(
"Debug details: %s",
expensive_details
)
Logging Around External Services
External dependencies are common failure points, so logging around them can be valuable. Record the operation and useful identifiers without dumping entire requests, response bodies, or credentials.
import logging
import time
logger = logging.getLogger(__name__)
def call_payment_service(order_id):
started = time.perf_counter()
logger.info(
"Payment request started order_id=%s",
order_id
)
try:
result = send_payment(order_id)
elapsed = (
time.perf_counter() - started
)
logger.info(
"Payment request completed "
"order_id=%s duration_ms=%.2f",
order_id,
elapsed * 1000
)
return result
except Exception:
logger.exception(
"Payment request failed order_id=%s",
order_id
)
raise
Logging in Libraries
Reusable libraries should generally create loggers and emit records without taking over the application's logging configuration. The application using the library should decide the final handlers, formatting, destinations, and severity policy.
# library_module.py
import logging
logger = logging.getLogger(__name__)
def connect():
logger.debug(
"Opening connection"
)
This keeps reusable code flexible and prevents imported modules from unexpectedly replacing the application's logging configuration.
Centralized Logging Configuration
Larger applications often keep logging configuration in one dedicated place. This makes changes to levels, formats, and handlers easier to manage.
import logging
def configure_logging():
logging.basicConfig(
level=logging.INFO,
format=(
"%(asctime)s | "
"%(levelname)s | "
"%(name)s | "
"%(message)s"
)
)
def main():
configure_logging()
logger = logging.getLogger(
__name__
)
logger.info(
"Application started"
)
if __name__ == "__main__":
main()
Console Logging for Containers
Applications deployed in containers commonly send logs to standard output and let the surrounding platform collect and route them. This separates application logging from log storage and retention decisions.
import logging
import sys
handler = logging.StreamHandler(
sys.stdout
)
handler.setFormatter(
logging.Formatter(
"%(asctime)s | "
"%(levelname)s | "
"%(name)s | "
"%(message)s"
)
)
logger = logging.getLogger(
"app"
)
logger.setLevel(
logging.INFO
)
logger.addHandler(
handler
)
logger.info(
"Container application started"
)
Structured Logging
As applications grow, logs are often consumed by monitoring or observability platforms. Structured logging represents event fields separately instead of relying entirely on free-form text.
Even when using the standard logging module, you can design messages around stable fields such as
request_id,
user_id,
operation,
duration_ms,
and
status.
This makes searching and aggregation easier.
logger.info(
"Order completed",
extra={
"order_id": order_id,
"user_id": user_id,
"status": "completed",
"duration_ms": duration_ms
}
)
Logging Concurrent Applications
Concurrent systems need enough context to distinguish operations that may be executing at the same time. Worker names, task IDs, request IDs, and job IDs can make concurrent logs much easier to trace.
import logging
import threading
logger = logging.getLogger(
__name__
)
def process_job(job_id):
thread_name = (
threading.current_thread().name
)
logger.info(
"Processing job=%s thread=%s",
job_id,
thread_name
)
Logging in Exception Boundaries
A practical pattern is to add context at the application boundary where the exception can be meaningfully interpreted, log the failure, and then decide whether to transform or re-raise the exception.
def create_order(order):
try:
return save_order(order)
except DatabaseError:
logger.exception(
"Could not create order_id=%s",
order["id"]
)
raise
Logging and exception handling serve different purposes. Logging records what happened; exception handling determines how the application responds.
Do Not Swallow Exceptions with Logging
One common mistake is to catch an exception, log it, and silently continue even though the caller needs to know that the operation failed.
# Risky
try:
process_order()
except Exception:
logger.exception(
"Order processing failed"
)
# Program continues as if
# the operation succeeded
Logging does not replace correct error handling. When the failure is not recoverable at the current layer, re-raise the exception or return an explicit failure result according to the application's design.
Logging a Complete Workflow
import logging
logger = logging.getLogger(
__name__
)
def process_order(order_id):
logger.info(
"Order processing started order_id=%s",
order_id
)
try:
validate_order(order_id)
logger.debug(
"Order validation completed order_id=%s",
order_id
)
charge_payment(order_id)
logger.info(
"Payment completed order_id=%s",
order_id
)
save_order(order_id)
logger.info(
"Order processing completed order_id=%s",
order_id
)
except PaymentError:
logger.exception(
"Payment failed order_id=%s",
order_id
)
raise
except Exception:
logger.exception(
"Unexpected order failure order_id=%s",
order_id
)
raise
Notice that the messages describe significant workflow boundaries instead of logging every individual line of execution.
Common Logging Mistakes
Using print Everywhere
print() is useful for simple scripts, but larger applications benefit from levels, handlers, formatting, and centralized control.
Logging Sensitive Data
Passwords, tokens, secrets, and private data should not be written to application logs.
Too Much Logging
Excessive logs increase noise, storage requirements, and operational cost while making important events harder to locate.
Too Little Context
Messages such as "failed" or "error occurred" provide little value without identifiers and meaningful operation context.
Duplicate Logs
Multiple handlers or logger propagation can cause the same record to be emitted more than once.
Swallowing Exceptions
Logging an exception and silently continuing can hide failures that should have been propagated to the caller.
Best Practices for Python Logging
- Use logging instead of scattered print statements for application diagnostics.
- Create module-level loggers with logging.getLogger(__name__).
- Choose log levels based on operational importance.
- Use DEBUG for detailed diagnostics and INFO for meaningful normal events.
- Use WARNING for recoverable or unexpected situations that deserve attention.
- Use ERROR for failed operations and CRITICAL only for severe application-level failures.
- Include useful identifiers and context in important messages.
- Use logger.exception() when traceback information is useful inside an exception handler.
- Prefer logging's argument-based formatting instead of eagerly building strings.
- Configure logging centrally in the application instead of independently in every module.
- Keep secrets and sensitive information out of logs.
- Choose file, console, or centralized destinations based on the deployment environment.
- Use rotation or retention policies when applications write persistent log files.
- Design log messages so that operators can search and correlate related events.
- Do not log the same failure repeatedly at every layer without adding useful context.
Practical Logging Checklist
- Can the log tell you what happened?
- Can you identify the operation, job, request, or resource involved?
- Is the selected severity level appropriate?
- Would the message still be useful during a production incident?
- Does it avoid passwords, tokens, secrets, and unnecessary personal information?
- Could the same event be logged multiple times because of propagation?
- Are high-volume DEBUG messages disabled when they are not needed?
- Does the logging destination fit the deployment environment?
Interview Questions to Prepare
- Why should logging be preferred over print() in production applications?
- What are the standard Python logging levels?
- What is the difference between a Logger, Handler, Formatter, and logging Level?
- What does logging.basicConfig() do?
- Why is logging.getLogger(__name__) commonly used?
- What is logger.exception() and when should it be used?
- What is logger propagation?
- Why can the same log message appear twice?
- How do you write logs to a file?
- How can you rotate log files?
- How can you add request IDs or job IDs to logs?
- Why should secrets never be logged?
- How should logging be designed for a containerized application?
- What is structured logging and why is it useful?
Summary
Python logging provides a structured way to observe application behavior. Instead of relying on temporary console messages, you can create named loggers, assign severity levels, attach handlers, control formatting, persist records, and include exception information.
Effective logging is mostly about judgment. Record significant events, provide enough context to diagnose failures, choose meaningful levels, avoid sensitive information, and keep configuration centralized. In production systems, logs should help developers and operators reconstruct what happened without overwhelming them with unnecessary information.
The goal is not to log everything. The goal is to make important application behavior observable, searchable, and understandable.