Chapters
Python114 chapters

Exercises

Logging

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

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())
Exercise 2

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())
Exercise 3

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())