pyodide: loading…

[concept]OOP & Tooling

Logging & Debugging

# theory

print debugging works until it doesn't. logging gives you levels (DEBUG, INFO, WARNING, ERROR) and you can send the output anywhere.

import logging, io

buf = io.StringIO()
handler = logging.StreamHandler(buf)
logger = logging.getLogger("demo")
logger.setLevel(logging.INFO)
logger.addHandler(handler)

logger.info("app started")
print(buf.getvalue().strip())

For debugging an exception, do not let it crash silently. Catch the specific error and handle it:

try:
    x = 1 / 0
except ZeroDivisionError:
    print("caught: division by zero")

Reading a traceback: start at the bottom. The last line is the error type and message. The lines above it are the call stack, newest last.

# examples [2]

# example 01 · logging to a buffer you can inspect

Attach a StreamHandler over StringIO and read it back

1
2
3
4
5
6
7
8
9
10
🐍
Loading PythonSetting up pandas & numpy...
# example 02 · catch the specific exception

Handle the error you expect, let the rest surface

1
2
3
4
5
6
7
8
9
🐍
Loading PythonSetting up pandas & numpy...

# challenges [2]

# challenge 01/02todo
Create a logger named 'demo' at INFO level with a StreamHandler writing to an io.StringIO buffer. Log the info message 'app started', then print the buffer's contents stripped.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
🐍
Loading PythonSetting up pandas & numpy...
# challenge 02/02todo
Wrap code that computes 1 / 0 in a try/except that catches ZeroDivisionError and prints exactly: caught: division by zero
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
🐍
Loading PythonSetting up pandas & numpy...