Relax, it’s all good, because we’re here to change all that. In this tutorial, we’ll cover everything you need to know about logging in Python without getting too technical or boring.
Before anything else: what is logging? It’s a fancy way of saying “keeping track of stuff” specifically, the events and messages that happen when your code runs. You might be wondering why you should bother with this, but trust us, it’ll save you hours (or even days) of head-scratching and hair-pulling in the long run.
So how do we use logging? Simple! We add some lines to our code that look like this:
# Import the logging module
import logging
# Set the logging level to DEBUG, which will show all messages
logging.basicConfig(level=logging.DEBUG)
# Log a debug message, which is used for detailed information during development
logging.debug("This is a debug message")
# Log an info message, which is used for general information during execution
logging.info("This is an info message")
# Log a warning message, which is used for potential issues that may cause problems
logging.warning("This is a warning message")
# Log an error message, which is used for errors that may cause the program to fail
logging.error("This is an error message")
# Log a critical message, which is used for critical errors that may cause the program to crash
logging.critical("This is a critical message")
These lines are called logging statements, and they tell Python to log certain messages at different levels of importance (or “severity,” if you prefer). The higher the level, the more important or urgent the message so debug messages are for minor details that might not be relevant in most cases, while critical messages indicate a serious problem that needs immediate attention.
Now, let’s say we have some code that does something complicated and potentially error-prone:
# This function calculates something based on the input value x
def calculate_something(x):
try:
# The result is calculated by multiplying x by 10 and dividing it by 3
result = (10 * x) / 3
except ZeroDivisionError:
# If x is 0, a ZeroDivisionError is raised and an error message is logged
logging.error("Zero division encountered!")
else:
# If no error is encountered, a success message is logged and the result is returned
logging.info("Result calculated successfully.")
return result
In this example, we’re using a `try-except` block to handle the possibility of dividing by zero (which would cause an error). If that happens, we log an error message; otherwise, we log an info message indicating that everything went smoothly. Pretty cool, right?
But wait there’s more! You can also customize your logging messages with variables and other fancy stuff:
# This function calculates a value by multiplying the input by 10 and dividing it by 3
def calculate_something(x):
try:
result = (10 * x) / 3 # Calculates the result by multiplying the input by 10 and dividing it by 3
except ZeroDivisionError: # Checks for a ZeroDivisionError
logging.error("Zero division encountered for input %d.", x) # Logs an error message if a ZeroDivisionError occurs
else:
logging.info("Result calculated successfully with value %f.", result) # Logs an info message if no error occurs
return result # Returns the calculated result
In this example, we’re using string formatting to insert the values of `x` and `result` into our messages. This can be really helpful for debugging or troubleshooting you can see exactly what input caused a problem (or which output was generated), without having to hunt through your code for clues.