Python's logging module is one of the lesser-known libraries, but it plays a crucial role in system logging. It helps track program activities and events that occur during execution. All this information is stored in a single file called a "log." This file can later be used to troubleshoot issues or debug code—a process known as logging in Python.
Why use Python's Logging library?
If you've started writing your own scripts, chances are you're using print()
statements to observe how variables change as your code executes. However, there are significant differences between using logging
and print()
:
print() vs logging: Key Differences
-
Purpose:
print()
: Typically used for simple outputs, like displaying results or quick debugging during development.logging
: Designed to track application execution states, providing detailed logs of events. It's more versatile and structured for long-term debugging and monitoring.
-
Persistence:
print()
: Outputs are limited to the console and disappear when the program ends. You'd need to manually redirect them to a file if required.logging
: Automatically saves messages to a log file (if configured), making it easy to review past events even after the program terminates.
-
Severity Levels:
print()
: No concept of severity; all messages have the same priority.logging
: Offers different log levels—Debug, Info, Warning, Error, Critical—allowing you to categorize messages by importance and easily filter critical events.
-
Configurability:
print()
: Limited to displaying content on the console.logging
: Provides full control over output format, message details, destination (console or file), and filtering based on severity levels.
-
Scalability:
print()
: Becomes cumbersome as applications grow, especially when dealing with multiple debug messages.logging
: Scales better, offering advanced features like logging to multiple destinations (files, remote servers), log file rotation, and customizable messages.
Logging levels in Python
Logging functions can record more than just text and numbers. These levels, listed from least to most severe, categorize the importance of each event:
- Debug: Provides information about program execution, useful for debugging unexpected outcomes.
- Info: Confirms the program is working as expected.
- Warning: Highlights unexpected events or potential issues.
- Error: Indicates a problem in the code, such as an inability to execute certain commands.
- Critical: Denotes the most severe issues, often critical enough to halt program execution.
Setting up Logging in Python
To effectively use logging, you need to configure the logger with some basic information:
import logging
logging.basicConfig(
filename="logfile.txt",
format='%(asctime)s %(message)s',
filemode='w',
level=logging.DEBUG
)
Configuration Parameters:
filename
: Name of the log file. If no path is specified, it will be saved in the same directory as the script.format
: Specifies what details to include in the log. For example, timestamps and error messages.filemode
: Mode for writing logs:'w'
for overwrite or'a'
for append.level
: Minimum severity level for logging messages (e.g.,DEBUG
,INFO
).
Using Python Logging: example
Here’s a complete example of logging in a Python script:
import logging
logging.basicConfig(
filename="logfile.txt",
format='%(asctime)s - %(levelname)s - %(message)s',
filemode='w',
level=logging.DEBUG
)
# Creating a logger object
logger = logging.getLogger()
# Log messages with different severity levels
logger.debug("This is a debug message")
logger.info("This is an informational message")
logger.warning("This is a warning message")
logger.error("An error occurred")
logger.critical("Critical error: program may crash")
Output (in the log file):
2024-11-17 12:45:52,835 - DEBUG - This is a debug message
2024-11-17 12:45:52,844 - INFO - This is an informational message
2024-11-17 12:45:52,845 - WARNING - This is a warning message
2024-11-17 12:45:52,845 - ERROR - An error occurred
2024-11-17 12:45:52,845 - CRITICAL - Critical error: program may crash
Logging exceptions
You can use the logging module to capture full exception traces:
import logging
logging.basicConfig(
filename="logfile.txt",
format='%(asctime)s - %(levelname)s - %(message)s',
filemode='w',
level=logging.DEBUG
)
logger = logging.getLogger()
try:
result = 5 / 0
except ZeroDivisionError:
logger.error("Exception occurred", exc_info=True)
Output (in the log file):
2024-11-17 12:07:11,045 - ERROR - Exception occurred
Traceback (most recent call last):
File "example.py", line 15, in <module>
result = 5 / 0
ZeroDivisionError: division by zero
When an exception occurs, the full traceback is logged, making debugging easier.
Suggestions or corrections are welcome! Feel free to leave your questions in the comments. Any contributions to improve our site, CodersLegacy, are greatly appreciated.
Copyright Notice: Unless otherwise indicated, all articles are original to this site, and reproduction must cite the source
Article link:http://pybeginners.com/article/what-is-logging-in-python-and-how-to-use-it/