Exercises
Logging
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Configure logging at INFO and log one info message, capturing it so you can print it.
Python
import logging
import io
captured = io.StringIO()
# configure and log
print(captured.getvalue().strip())basicConfig takes stream= and force=True.
import logging
import io
captured = io.StringIO()
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s",
stream=captured, force=True)
logging.getLogger("demo").info("started")
print(captured.getvalue().strip())Exercise 2Passed
Set the level so the debug line is hidden and the warning is shown.
Python
import logging
import io
captured = io.StringIO()
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s %(message)s",
stream=captured, force=True)
log = logging.getLogger("demo")
log.debug("hidden")
log.warning("shown")
print(captured.getvalue().strip())Raise the level so DEBUG falls below it.
import logging
import io
captured = io.StringIO()
logging.basicConfig(level=logging.WARNING, format="%(levelname)s %(message)s",
stream=captured, force=True)
log = logging.getLogger("demo")
log.debug("hidden")
log.warning("shown")
print(captured.getvalue().strip())Exercise 3Passed
Log the failure with its traceback, from inside the except block.
Python
import logging
import io
captured = io.StringIO()
logging.basicConfig(level=logging.ERROR, format="%(levelname)s %(message)s",
stream=captured, force=True)
log = logging.getLogger("demo")
try:
int("abc")
except ValueError:
log.error("could not parse")
print("Traceback" in captured.getvalue())There is a method that is error() plus the traceback.
import logging
import io
captured = io.StringIO()
logging.basicConfig(level=logging.ERROR, format="%(levelname)s %(message)s",
stream=captured, force=True)
log = logging.getLogger("demo")
try:
int("abc")
except ValueError:
log.exception("could not parse")
print("Traceback" in captured.getvalue())