
Fill in
A Logbook, Not Prints
Debug prints are great for a quick look, but you have to delete them
afterwards. Real programs keep a log instead, using the logging
module. Every message gets a level:
| Level | Use it for |
|---|---|
DEBUG |
detailed evidence for detectives |
INFO |
normal events ("saved the quest") |
WARNING |
something odd, but we coped |
ERROR |
something failed |
CRITICAL |
the program can't go on |
import logging
logging.basicConfig(level=logging.INFO,
format="%(levelname)s: %(message)s")
log = logging.getLogger("lighthouse")
log.debug("hidden: below INFO")
log.warning("fuel is low") # WARNING: fuel is low
One setting, level=, chooses how much you see. Set it to DEBUG
while hunting a bug and to WARNING when all is well. No need to
delete anything! Logs can also go to a file, with the time on every line.
force=True in basicConfig replaces any earlier setup. It's handy
when you run a script again and again, like here.
Assignment
Fill in each ___:
- Show messages of level
DEBUGand up. - Get the logger named
"lighthouse"withlogging.getLogger. - In
refuel, log the evidence line at debug level. - Log the negative-fuel message at error level.
- Log the overflow message at warning level.
Fill in each ___:
- Show messages of level
DEBUGand up. - Get the logger named
"lighthouse"withlogging.getLogger. - In
refuel, log the evidence line at debug level. - Log the negative-fuel message at error level.
- Log the overflow message at warning level.
main.py Python sleeping
Press Run to try your code, then Check to test it.