Python, properly · Chapter 22 of 42
Debugging and logging
By the end of this chapter you can read a long traceback to the line that matters, step through a running program with breakpoint() and pdb, and record what a program does with the logging module instead of print. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Code that holds up
- 5 tasks
- Python
- In the all labs plan
The first 2 chapters of Python, properly are free. This one comes with the all labs plan.
Why you need this
Bhavna runs the riders' pay script every night, and some nights the numbers are wrong. There is no crash and no traceback; the answer is just wrong. Meanwhile Farah wants to know what the order service did overnight: which orders it settled, which totals it could not read, and when.
Your tools so far are reading tracebacks (chapter 1) and adding print calls. Prints are fine for a minute, but they are messy to add and remove, they go to the same place as the program's real output, and they say nothing about when or how serious. Debugging and logging are the professional versions of both.
What you build: 5 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
fix_average.py: a wrong answer, found with the debugger
fix_average.py should print the average delivery time of its five deliveries in whole minutes, rounded down: Average delivery: 47 minutes. It prints a much smaller number, with no traceback.
Put breakpoint() inside the loop of average_minutes, run the file, and watch total with the debugger's p and n commands until you see where it goes wrong. Fix that line, and remove the breakpoint.
The check runs the file and also calls average_minutes on other deliveries.
- Task 2
fix_items.py: read the traceback
fix_items.py prints the total of each of the kitchen's typed orders, but it crashes on the third one. Run it, read the traceback from the bottom to the line in your code, and fix parse_items, the function that breaks.
The kitchen's rules: an item with no :quantity means 1 (masala-chaas means one masala-chaas), and spaces around an item are ignored. Fixed, it prints:
roti:4;dal-tadka:1 -> 200, veg-thali:2 -> 420, masala-chaas;roti:2 -> 70 and dal-tadka:1; roti:3 -> 185, one per line.
Careful: after the first fix, run it again: a second traceback is waiting. The check also calls order_total on other orders.
- Task 3
kitchen_log.py: log instead of print
kitchen_log.py, when run, checks today's dishes, TODAY = ["dal-tadka", "fish-fry", "roti", "jain-thali", "misal-pav"], against /workspace/data/menu.json and logs what it finds.
Set up logging once, at the start: the file kitchen.log in the folder it is run from, level INFO, format "%(levelname)s %(name)s: %(message)s". Use a logger named kitchen. For each id, log at DEBUG checking <id>, then at INFO <dish name> is ready if the dish is available, or at WARNING <dish name> is not available if not. So kitchen.log starts INFO kitchen: Dal Tadka is ready, then WARNING kitchen: Bombil Fry is not available.
The script prints nothing. The check runs it in an empty folder and reads kitchen.log.
- Task 4
settle.py: errors into the log
Write settle(totals): totals is a list of texts; it returns the sum of the ones that are whole numbers. For each one that is not, it logs an error with the exception's traceback, using a logger made with logging.getLogger(__name__), with the message could not read total followed by the text as %r shows it (for example could not read total 'Rs 477'), and skips it.
settle(["240", "Rs 477", "180", "₹230", "", "90"]) returns 510 and logs three errors, each with its traceback. settle prints nothing.
- Task 5 · interview question
Interview: fix_logging.py, the log file that never appears
fix_logging.py should write three lines to night.log, in the folder it is run from: INFO starting the night report, INFO orders read: 600 and WARNING 2 orders without a rider. Run it: there is no night.log, and a WARNING line shows up in the terminal instead.
Fix it so night.log gets exactly those three lines, keeping the three log calls and their messages.
Be ready to explain why basicConfig did nothing.
What you will learn
- Long tracebacks: several frames, and two exceptions chained together.
- breakpoint() and pdb: pausing a program to look inside it.
- logging: levels, basicConfig, named loggers, log files.
- logger.exception: an error and its traceback, written to the log.
More in Code that holds up
Build "Debugging and logging" yourself
DabbaDrop, a Mumbai tiffin startup, runs on Excel and WhatsApp. You are its first Python developer. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of Python, properly are free. This one comes with the all labs plan.