Editor

Add Logging to a Function

Beginner · Write the code · from Python Logging: Stop Using print() for Debugging

From the lesson: Python Logging: Stop Using print() for Debugging

Every airplane has a flight recorder - a "black box" that silently records everything that happens during a flight. If something goes wrong, investigators can replay the recording to figure out exactly what happened and when.

Read the lesson

Write a function called divide(a, b) that divides two numbers and uses logging:

1. Set up basicConfig with level=logging.DEBUG, format='%(levelname)s: %(message)s', stream=sys.stdout, and force=True (import sys so the log messages appear in the output panel)

2. At the start of the function, log a DEBUG message: 'Dividing %s by %s', a, b

3. If b is 0, log an ERROR message: 'Division by zero!' and return None

4. Otherwise, log an INFO message: 'Result: %s', result and return the result

Then call print(divide(10, 2)) and print(divide(5, 0)).

import logging
# Set up logging here
def divide(a, b):
pass # Your code here
print(divide(10, 2))
print(divide(5, 0))

More Logging exercises

All Python exercises · 50 practice problems · Error Handling quiz