Python Logging Instead of Print For Debugging
Debugging is the process of finding and fixing errors in your code. Print statements are a common way to debug by printing out values or messages to the console. However, print statements have some limitations and drawbacks:
They can clutter up your code and make it less readable.
They can affect the performance of your program by slowing it down or changing its behavior.
They can be hard to manage when you have multiple print statements in different modules or functions.
They can be lost or overwritten when you run your program in different environments or platforms.
Logging is a better alternative to print statements for debugging because it allows you to:
Control the level of detail and format of your output by using different log levels (such as DEBUG, INFO, WARNING, ERROR, CRITICAL) and handlers (such as StreamHandler, FileHandler, etc.).
Filter out unwanted messages by using loggers (such as root logger, named logger) and filters.
Record useful information such as timestamps, module names, line numbers, function names, etc. by using formatters.
Save your output to a file or send it to other destinations such as email, database, etc. by using handlers.
To use logging in Python, you need to import the logging module and configure it according to your needs. Here is a simple example:
import logging
# Configure logging
logging.basicConfig(filename="debug.log", level=logging.DEBUG)
# Create a logger object
logger = logging.getLogger("example")
# Log some messages
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")
This will create a file named debug.log that contains something like this:
DEBUG:example:This is a debug message
INFO:example:This is an info message
WARNING:example:This is a warning message
ERROR:example:This is an error message
CRITICAL:example:This is a critical message
# Logging Code For Zero Division Error
import logging
a = 10
b = 0
try:
c = a / b
except Exception as e:
logging.error("Exception Occurred", exc_info=True) # At default it is True
# Console output
ERROR:root:Exception Occurred # If exc_info=False then only this message will print
Traceback (most recent call last):
File "C:\Users\Name\Desktop\logging_code.py", line 5, in <module>
c = a / b
ZeroDivisionError: division by zero
# Console output
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(a/b)
ZeroDivisionError: division by zero
I hope this helps you understand how to use logging instead of print for debugging in Python. Do you have any questions or feedback?
Comments
Post a Comment