Logging and Debugging
Python Logging and PEP 282
BOTIE
The application can then choose an event destination and detail level while library code describes what happened. A traceback provides different evidence: an exception type and call path. More recorded text does not automatically make either form more useful; the context must explain the operation.
Sources for this history
The Worker Said Only “Something Went Wrong”
Botie's worker skipped a report, but the message identifies neither the batch nor the failed operation. Printing the whole request would reveal data the diagnosis does not need.
We need a useful account of the event and a way to follow the failure to its cause. The information should be chosen for that purpose rather than recorded indiscriminately.
The blocks filter local example records and do not send logs. Messages here contain approved event text; real exception messages can include private input and need separate review.
Step 1 of 1
Record useful context without the whole payload
Severity and an appropriate batch identity can describe the event while private fields stay out.
| Field | Example | Routine output |
|---|---|---|
| level | ERROR | Include |
| batch_id | batch-7 | Include if appropriate |
| payload | Private record content | Exclude |
level
- Example
- ERROR
- Routine output
- Include
batch_id
- Example
- batch-7
- Routine output
- Include if appropriate
payload
- Example
- Private record content
- Routine output
- Exclude
Follow the traceback before guessing
Severity selects which events matter for this view. Field selection keeps useful context while leaving the attached private placeholder out.
Keep useful report logs
A report failed, but a message saying "error" gives little help. Keep its report ID and a short description so the failure can be found. The supplied events also contain a private-token placeholder that should stay out of the public output.
BOTIE
Selected log events containing only public fields
- level
- WARNING
- report_id
- R11
- message
- No readings for south
- level
- ERROR
- report_id
- R12
- message
- Temperature field rejected
| level | report_id | message |
|---|---|---|
| WARNING | R11 | No readings for south |
| ERROR | R12 | Temperature field rejected |
Follow the operations
1. Report events with private placeholders
- level
- INFO
- report_id
- R10
- message
- Report completed
- private_token
- placeholder only
- level
- WARNING
- report_id
- R11
- message
- No readings for south
- private_token
- placeholder only
- level
- ERROR
- report_id
- R12
- message
- Temperature field rejected
- private_token
- placeholder only
level report_id message private_token INFO R10 Report completed placeholder only WARNING R11 No readings for south placeholder only ERROR R12 Temperature field rejected placeholder only 2. Least severe event to keep
WARNING
3. Choose event severity
- 0false
- 1true
- 2true
4. Keep flagged entries
- level
- WARNING
- report_id
- R11
- message
- No readings for south
- private_token
- placeholder only
- level
- ERROR
- report_id
- R12
- message
- Temperature field rejected
- private_token
- placeholder only
level report_id message private_token WARNING R11 No readings for south placeholder only ERROR R12 Temperature field rejected placeholder only 5. Fields allowed in the displayed log
- 0level
- 1report_id
- 2message
6. Select fields for a record
- level
- WARNING
- report_id
- R11
- message
- No readings for south
- level
- ERROR
- report_id
- R12
- message
- Temperature field rejected
level report_id message WARNING R11 No readings for south ERROR R12 Temperature field rejected 7. Result
- level
- WARNING
- report_id
- R11
- message
- No readings for south
- level
- ERROR
- report_id
- R12
- message
- Temperature field rejected
level report_id message WARNING R11 No readings for south ERROR R12 Temperature field rejected
The blocks filter local example records and do not send logs. Messages here contain approved event text; real exception messages can include private input and need separate review.
1. Follow the traceback before guessing
A traceback shows the call path leading to an exception. Read the type and message, then inspect the frames connecting it to your code. The last line may describe a failed conversion while earlier frames explain which operation supplied that value.
Reproduce the failure with a suitable small input, then retain a regression test. A debugger can pause execution to inspect local state. Avoid leaving permanent output that prints every record merely to locate one defect. Tracebacks and exception messages can themselves contain private values.
2. Separate the event from its destination
A logger names an event source. A level describes its severity. A handler sends accepted records to a destination such as a stream or file. The application normally configures these decisions; a reusable library should not repeatedly reconfigure global logging.
The standard levels progress from DEBUG through INFO, WARNING, ERROR and CRITICAL. A WARNING threshold includes more severe errors. print remains appropriate for ordinary command-line results; operational logging has a different role.
Capture operational events in memory
The example configures one named logger temporarily and restores its settings.
import io
import logging
stream = io.StringIO()
logger = logging.getLogger("course.report.example")
previous_level = logger.level
previous_propagation = logger.propagate
handler = logging.StreamHandler(stream)
handler.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.propagate = False
try:
logger.debug("Detailed calculation")
logger.info("Batch %s accepted", "batch-7")
logger.warning("Batch %s needs review", "batch-8")
print(stream.getvalue(), end="")
finally:
logger.removeHandler(handler)
handler.close()
logger.setLevel(previous_level)
logger.propagate = previous_propagationINFO Batch batch-7 accepted
WARNING Batch batch-8 needs reviewDEBUG is below the selected level. No file or remote logging service is used.
Check yourself
Questions on Parts 1 and 2
Question 1 of 2
Which pass that threshold?
Question data
Minimum level: WARNING. Events: DEBUG, WARNING, ERROR.3. Preserve the failure without leaking its input
An appropriate operation or event ID can connect records without copying a request. Inside an except block, logger.exception includes exception information. Use that only when the full diagnostic trace is suitable for the destination and its access policy.
A validation exception may include the rejected input. Logging its whole string can expose credentials or private records. Select an error category and reviewed fields for routine diagnostics. Avoid logging the same failure at every layer and then again at the application boundary.
Report a category and invented batch ID
The rejected field is not copied into the diagnostic.
def parse_count(text):
return int(text)
try:
parse_count("not-a-count")
except ValueError as error:
diagnostic = {"batch_id":"batch-7", "error_type":type(error).__name__}
print(diagnostic){'batch_id': 'batch-7', 'error_type': 'ValueError'}A protected diagnostic system could preserve a separately reviewed traceback. Logging also does not replace recovery or propagation behavior.
4. Test the information contract
Capture records with an in-memory handler or unittest's assertLogs. Check useful facts such as level and selected context rather than requiring an uncontrolled timestamp. Test that private fields are excluded as well as checking which event is present.
A level is not a privacy policy. ERROR can leak a token just as DEBUG can. Keep access and retention appropriate, and choose event volume for actual diagnosis rather than logging every successful row without a reason. The workshop models severity and field selection, not every detail of Python's logger hierarchy.
Check yourself
Questions on Parts 1 to 4
Question 1 of 4
What needs review before logging its complete string?
Question data
A validation exception can contain rejected input.Try it with Botie
Build with Botie
Write and run Python