Logging and Diagnostics
Understand Python logging levels, configure loggers and handlers, record exceptions, and diagnose problems with useful messages.
In this lesson, you will learn
- ✓Explain why logging is useful for debugging and diagnosing applications.
- ✓Distinguish DEBUG, INFO, WARNING, ERROR, and CRITICAL logging levels.
- ✓Configure loggers, handlers, and formatters for predictable output.
- ✓Use variable data, exception tracebacks, and appropriate logging methods.
- ✓Choose useful diagnostic messages while avoiding duplicate logs and sensitive information.
1. What is logging and why do we need it?
Logging is the practice of recording messages about a program's execution. A message might indicate that an application started, a file was processed, a configuration value was missing, or an operation failed.
Python provides the built-in logging module, so you do not need to install an additional package to use it.
You can use print() to display information while learning Python or debugging a small script. However, print() does not provide a standard severity system, and you must manually manage message formatting and output destinations.
Logging provides a more structured approach. You can choose which messages to record, include useful context, and configure whether messages appear in the terminal or are sent to another destination.
A log message does not automatically fix a problem. Its purpose is to give you evidence that helps you understand what happened and decide what to do next.
Your first log message
import logging loads Python's standard logging module. basicConfig() configures the root logging system for this standalone demonstration. level=logging.WARNING sets the root logger's threshold to WARNING. format='%(levelname)s:%(message)s' displays the severity followed by the message. stream=sys.stdout directs the displayed log output to standard output. force=True replaces existing root logging configuration. It is useful for an isolated demonstration, but should not be used casually in an application whose logging has already been configured. getLogger('demo') returns a named logger. Its warning message is emitted through the configured logging system.
Note
2. Understanding the five logging levels
Logging levels indicate the severity or importance of a message. Python provides five commonly used levels: DEBUG, INFO, WARNING, ERROR, and CRITICAL.
DEBUG (10) is used for detailed diagnostic information, such as intermediate values that help investigate a problem.
INFO (20) describes normal application events, such as a successful startup or completed operation.
WARNING (30) indicates an unexpected condition or a potential problem that does not necessarily prevent the operation from continuing.
ERROR (40) indicates that an operation failed or encountered a significant problem.
CRITICAL (50) indicates a very serious problem that may prevent the application or a major component from continuing.
When a logger is set to a particular threshold, it normally processes messages at that level and above, subject to handler levels, filters, and other logging configuration. For example, a WARNING threshold excludes DEBUG and INFO messages but allows WARNING, ERROR, and CRITICAL messages.
Compare the logging levels
The logger is configured to accept DEBUG messages and higher. Each call creates a record with the corresponding severity. The formatter displays the level name followed by a colon and the message. The lines appear in the order the logging calls execute. In a real application, choose a level that communicates the seriousness of the event rather than marking every message as an error.
Note
3. Loggers, handlers, and formatters
A logger is the object your code calls to create log records. You usually obtain one using logging.getLogger(__name__), which names the logger after the current module.
A handler determines where a log record is sent. StreamHandler can send messages to a stream, FileHandler can write messages to a file, and other handlers can send records to additional destinations.
A formatter determines how the record appears. It can include the level name, logger name, timestamp, and message.
A filter can provide additional rules for deciding which records should be processed.
The logging system separates these responsibilities so that application code can create messages without needing to know exactly where they will be stored.
Logger levels and handler levels serve different purposes. A record must pass the relevant logger-level checks and handler-level checks before that handler emits it. Logger propagation can also send records to ancestor loggers' handlers.
Configure a logger explicitly
getLogger('checkout') retrieves a logger named checkout. logger.setLevel(logging.INFO) allows INFO and more severe records through the logger's level check. logger.propagate = False prevents this logger's records from being passed to ancestor loggers' handlers. StreamHandler(sys.stdout) sends output to standard output. The handler's INFO level allows INFO and more severe records through that handler. The formatter adds the severity, logger name, and message. Because the logger has one configured handler and propagation is disabled, this standalone example emits one formatted line.
Note
4. Formatting messages and recording variable values
Useful diagnostic messages explain what the program was doing and provide enough context to investigate a problem.
Instead of logging only 'Failed', include relevant details such as the operation name, a safe identifier, or the number of items processed. Avoid recording sensitive information such as passwords, authentication tokens, or private data.
Python's logging methods accept a message format and additional arguments. For example, logger.info('Processed %d records', count) lets logging format the value when the record is emitted.
Using logging's argument-based formatting is generally preferable to eagerly building a string with an f-string for a message that might be filtered out. The logging call can defer message interpolation until the record is formatted.
The message placeholders must match the supplied values. Use %s for string-style representation and %d for integer-style formatting when appropriate. Invalid formatting can produce logging errors when the record is formatted.
Record useful diagnostic context
record_count contains the integer 125. filename contains the string customers.csv. The logging call passes the format string and values separately. The formatter combines the message with the configured severity prefix. The message identifies the operation's result without logging the contents of the customer records.
Note
5. Logging exceptions and tracebacks
When an operation raises an exception, the exception type and message often explain what went wrong. A traceback also shows the sequence of calls that led to the failure.
logger.exception('...') is designed to be used inside an except block. It logs a message at ERROR level and includes exception information from the active exception context.
You can also use logger.error('...', exc_info=True) inside an except block when you need to include exception information with an ERROR message.
Do not use logger.exception() as a replacement for handling an exception. Decide whether the program should recover, retry, report the failure, or allow the exception to propagate.
Avoid logging an exception multiple times at several layers without adding useful context. Duplicate tracebacks make diagnostics noisy and can obscure the original failure.
Log a caught exception
int('abc') raises ValueError because abc is not a valid integer representation. The except block catches that exception. logger.exception() records the error message and traceback for the active exception. The exact traceback includes runtime-dependent file names and line numbers, so it is not reproduced as a fixed output line here. After the exception is handled, execution continues to the print statement. This example handles the conversion failure deliberately. If the exception were not caught, the program would normally terminate with an unhandled exception.
Note
6. Practical logging habits and troubleshooting
Choose a severity that accurately reflects the event. Normal progress usually belongs at INFO; diagnostic details belong at DEBUG; a recoverable unexpected condition may belong at WARNING; and a failed operation may warrant ERROR.
Use logging.getLogger(__name__) in modules so log records can be associated with their source module.
Configure the logging system once in the application entry point. Avoid calling basicConfig() repeatedly throughout the application. In ordinary use, basicConfig() generally does nothing if the root logger already has handlers unless force=True is supplied.
Use handlers and formatters to decide where messages go and how they look. A message not appearing in the terminal might have been filtered by the logger level, handler level, a filter, or output configuration.
If log lines appear twice, inspect whether multiple handlers are attached or whether the record is propagating to a parent logger whose handler emits it again.
If a DEBUG message is missing, check the effective logging level and the handler configuration. Setting a logger to DEBUG alone does not guarantee that every handler will emit the record.
In production applications, protect log files and log destinations appropriately. Logs may contain operational information and should not expose secrets or unnecessary personal data.
Use a module-level logger
When this file is imported as app, __name__ is normally app. The logger is associated with the module name. This module does not configure any handlers or logging level itself. The application that runs this code should configure logging, usually near its entry point. If no suitable configuration allows the INFO record to be emitted, calling start_service() may not produce a visible line.
Caution
Common pitfalls to avoid
Real debugging lessons and exact syntax contrasts to avoid runtime bugs
#1 Using print() for every diagnostic message in a larger application.
Why it happens: The logging module provides severity levels, configurable destinations, timestamps, and structured diagnostic handling that scales better than scattered print calls.
Key takeaway: Use the logging module when you need severity levels, consistent formatting, or configurable destinations.
#2 Assuming logger.setLevel(logging.INFO) controls every handler by itself.
Why it happens: Logger and handler thresholds are separate filters; a message may be accepted by the logger but rejected by its handler.
Key takeaway: Check the logger threshold, handler thresholds, filters, and propagation settings when diagnosing missing output.
#3 Adding handlers repeatedly.
Why it happens: Adding the same handler repeatedly can duplicate each log message, so configure handlers once or check existing configuration.
Key takeaway: Configure handlers centrally and avoid registering another handler each time a function executes.
#4 Using logger.exception() outside an exception handler.
Why it happens: logger.exception() includes exception information and is intended for use inside an exception handler where exception context is available.
Key takeaway: Call logger.exception() inside an except block when you want the active exception traceback.
#5 Logging only vague messages such as 'Failed'.
Why it happens: A vague message lacks the context needed to diagnose a failure; include relevant operation, identifier, and safe state information.
Key takeaway: Include useful, safe context such as the operation and resource identifier.
#6 Assuming a missing log line means the logging call never executed.
Why it happens: A log call may execute but be filtered by levels, handlers, propagation settings, or output configuration.
Key takeaway: Check severity thresholds, handler configuration, filters, propagation, and destination.
#7 Logging sensitive data to help diagnose a problem.
Why it happens: Logs can persist in files or external systems, so avoid passwords, tokens, personal data, and other secrets in log messages.
Key takeaway: Record only the context needed for troubleshooting and exclude credentials, secrets, and unnecessary personal information.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is logging in Python?
Q2:Explain the five standard logging levels.
Q3:What is the difference between a logger, handler, and formatter?
Q4:What happens when the logging level is set to WARNING?
Q5:What is the difference between print() and logging?
Q6:What is logger.exception() used for?
Q7:Why use logging.getLogger(__name__)?
Q8:Why might a log message appear twice?
Q9:What is basicConfig() used for?
Q10:What makes a good diagnostic message?
Key takeaways
- Python's logging module records structured messages about program execution.
- The five standard levels are DEBUG, INFO, WARNING, ERROR, and CRITICAL.
- Logger thresholds, handler thresholds, and filters determine which messages are emitted.
- Loggers create records, handlers route them, and formatters control their presentation.
- Use logger.exception() inside an except block when you need an exception traceback.
- Configure logging centrally and avoid registering handlers repeatedly.
- Useful diagnostic messages provide context without exposing secrets.
- Passing tests and having logs does not guarantee a defect-free application; both are tools for investigating and verifying behavior.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: