Python / Maintainable systems / Lesson 21
Logging and diagnostic boundaries
Design Python logging events and test diagnostic ownership.
On this page
Lesson goals
- Trace logger, handler, level, and propagation.
- Test safe exception diagnostics.
- Trace logger levels, handler routing, and propagation using isolated fixtures.
- Test safe diagnostic content and exception recording without brittle traceback matching.
Trace the logging pipeline
Logging records events for later diagnosis, while the application decides where those events go. A logger names the source, a level describes severity, and a handler sends records to a destination using a formatter. The effective logger level and handler level both affect which events appear. Design messages around a useful event and its safe context, not around a dump of every object in memory.
Capture a controlled event
The example configures a named logger with a stream handler writing to an in-memory buffer. Its explicit level admits the informational event, and the handler formats only the level and message. Propagation is disabled here so surrounding application configuration cannot duplicate the demonstration. This isolated configuration makes the expected result testable without writing a file or relying on the machine’s console settings.
import io
import logging
buffer = io.StringIO()
logger = logging.getLogger("lesson.event")
logger.handlers.clear()
logger.propagate = False
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(buffer)
handler.setFormatter(logging.Formatter("%(levelname)s:%(message)s"))
logger.addHandler(handler)
logger.info("processed %s items", 3)
print(buffer.getvalue().strip())
INFO:processed 3 items
A private in-memory stream makes the observed record deterministic.
Separate library configuration
A reusable library should obtain a named logger and let the application configure destinations and verbosity. Configuring the root logger or attaching ordinary output handlers inside a library can interfere with its host. Logger names form a hierarchy, and records normally propagate to ancestor handlers. If both a child and an ancestor have output handlers, one event may appear twice; inspect that path before removing useful diagnostic calls.
Record exception context
Log exceptions where a layer has enough context to explain the failure and decide whether to propagate it. logger.exception includes exception information and is intended for use inside an exception handler. Avoid logging the same exception at every layer unless each record adds useful context. The example captures a synthetic ValueError, records a short message, and checks that exception information reached the buffer rather than relying on an exact traceback format.
import io
import logging
buffer = io.StringIO()
logger = logging.getLogger("lesson.error")
logger.handlers.clear()
logger.propagate = False
logger.setLevel(logging.ERROR)
logger.addHandler(logging.StreamHandler(buffer))
try:
raise ValueError("bad example")
except ValueError:
logger.exception("validation failed")
print("validation failed" in buffer.getvalue())
print("ValueError: bad example" in buffer.getvalue())
True
True
Both the event message and exception text are captured inside the handler.
Verify safe diagnostics
Treat logs as data with an audience and retention policy. Never include credentials or full untrusted records merely for convenience; select a safe identifier and the operation outcome. Test an expected event and the absence of sensitive fields using synthetic input. When a message is missing, inspect logger level, handler level, propagation, and destination in that order, then repeat the original operation in its actual launch context.
Trace records through loggers and handlers
A logger creates records for events that pass its effective level. Handlers decide where records go and can apply their own levels and filters; formatters produce their displayed representation. A child logger’s record can propagate to ancestor handlers. If both the child and its parent have handlers, a single event may appear twice. Inspect logger levels, handler placement, and propagation before changing configuration, because disabling propagation can also prevent intended parent processing.
Library code should normally obtain a named logger rather than configure global logging as an import side effect. The application owns handler configuration and destinations. Tests should isolate their synthetic logger, handlers, and stream, then restore or remove them so one test does not affect another. Avoid relying on the root logger’s existing configuration when a self-contained fixture can make the path explicit.
Use levels and structured context deliberately
Levels express the operational importance of an event, not a substitute for a meaningful message. A logger can discard a record below its effective level before handlers see it; a handler can independently discard a record below its own level. Test the level combination that matters to the application. Include stable identifiers or fields that help correlate a synthetic operation, but avoid logging secrets, complete personal records, or raw untrusted payloads by default.
Parameterized logging such as logger.info("count=%s", count) lets the logging system format the message when the record is handled. It is not a guarantee that every argument computation is free: expensive expressions are evaluated before the call. Guard genuinely expensive diagnostic preparation when needed and measure the actual workload. If structured fields are part of a contract, define their names, types, and redaction policy rather than relying on an incidental text format.
Record exceptions without brittle tests
logger.exception is intended for an active exception handler and includes exception information. logging.error with exc_info=True can also attach the active exception. A test can capture a handler’s output or records and check a controlled message and exception type without matching an entire traceback containing line numbers and machine-specific paths. Verify separately whether the exception should propagate, be translated, or be handled; logging it does not decide control flow.
Avoid logging the same exception at every layer unless the operational policy calls for it. Duplicate records can obscure the first failure and increase noise. A boundary that handles an error may record a safe category and correlation identifier while preserving the cause for authorized diagnosis. Do not include secrets or full request bodies merely to make a test convenient. The examples use synthetic messages and in-memory streams only.
Control diagnostic boundaries
A log is an observable data flow. Choose what crosses that boundary, who can access it, and how long it is retained in the actual system. Redaction should occur before sensitive values reach handlers, not only in a display view. A formatter or filter can contribute to a policy, but a single example is not proof that all paths are protected. Avoid using logging as a replacement for input validation, authorization, or a durable audit system with its own requirements.
Propagation affects routing, not the original event’s correctness. A child with propagate=False will not send its record to ancestor handlers, so ensure it has an appropriate local handler if its events must be retained. When using a parent handler only, avoid adding a redundant child handler. Test the intended count and destination of records with a synthetic fixture. If logging itself fails, follow the application’s documented operational policy rather than silently asserting that the event was stored.
Verify destinations, levels, and errors
Build tests for a message below and at the configured level, a child with and without propagation, and an exception recorded inside an active handler. Count records or capture a StringIO stream to verify routing without writing to a real log file. Clean up handlers after the test. For redaction, use a synthetic secret marker and assert that the marker is absent from every captured destination covered by the fixture.
The complete programs below use Python 3.11-compatible standard-library logging and fixed synthetic values. Each configures a distinct local logger and in-memory stream; outputs were checked in fresh local processes. They illustrate logging mechanics and do not prove production retention, confidentiality, or delivery. Verify those properties with the actual deployment configuration and access controls.
20 worked examples
1. Capture a synthetic record
Problem: Write one informational event to an isolated in-memory logging handler.
- The logger admits INFO and the handler writes to StringIO.
- The formatter adds the level and message, producing INFO:ready.
import logging, io
stream = io.StringIO()
logger = logging.getLogger("demo.one")
logger.setLevel(logging.INFO)
logger.propagate = False
handler = logging.StreamHandler(stream)
handler.setFormatter(logging.Formatter("%(levelname)s:%(message)s"))
logger.addHandler(handler)
logger.info("ready")
print(stream.getvalue().strip())
logger.removeHandler(handler)
INFO:ready
Why this result follows: A local handler and formatter make the record’s destination and representation observable.
2. Filter at the logger level
Problem: Compare an informational and warning event at a warning logger threshold.
- The INFO event is below the logger’s WARNING level and is discarded.
- The WARNING event reaches the handler and writes shown.
import logging, io
s = io.StringIO()
l = logging.getLogger("demo.level")
l.setLevel(logging.WARNING)
l.propagate = False
h = logging.StreamHandler(s)
l.addHandler(h)
l.info("hidden")
l.warning("shown")
print(s.getvalue().strip())
l.removeHandler(h)
shown
Why this result follows: The logger’s effective level determines which events are admitted to its handlers.
3. Filter at the handler level
Problem: Compare warning and error records at an error-only synthetic handler.
- The logger admits both records because its threshold is DEBUG.
- The handler discards WARNING and writes the ERROR message.
import logging, io
s = io.StringIO()
l = logging.getLogger("demo.handler")
l.setLevel(logging.DEBUG)
l.propagate = False
h = logging.StreamHandler(s)
h.setLevel(logging.ERROR)
l.addHandler(h)
l.warning("hidden")
l.error("shown")
print(s.getvalue().strip())
l.removeHandler(h)
shown
Why this result follows: A handler can apply a stricter level after the logger admits a record.
4. Format a parameterized message
Problem: Log a fixed synthetic count using a message template and argument.
- The logger creates an INFO record with the template and count argument.
- The handler formats the argument into the displayed message count=3.
import logging, io
s = io.StringIO()
l = logging.getLogger("demo.args")
l.setLevel(logging.INFO)
l.propagate = False
h = logging.StreamHandler(s)
l.addHandler(h)
l.info("count=%s", 3)
print(s.getvalue().strip())
l.removeHandler(h)
count=3
Why this result follows: Parameterized logging separates the message template from the arguments used for its formatting.
5. Include the logger name
Problem: Capture a synthetic event with the logger name in its formatted output.
- The record is created by the named logger demo.name.
- The formatter combines that name with the message ready.
import logging, io
s = io.StringIO()
l = logging.getLogger("demo.name")
l.setLevel(logging.INFO)
l.propagate = False
h = logging.StreamHandler(s)
h.setFormatter(logging.Formatter("%(name)s:%(message)s"))
l.addHandler(h)
l.info("ready")
print(s.getvalue().strip())
l.removeHandler(h)
demo.name:ready
Why this result follows: A formatter can expose record attributes without changing the event’s original message text.
6. Propagate to a parent
Problem: Send a child event to a single synthetic parent handler.
- The child admits INFO and propagates the record upward.
- The parent handler writes the event once to the stream.
import logging, io
s = io.StringIO()
parent = logging.getLogger("route")
child = logging.getLogger("route.child")
parent.setLevel(logging.INFO)
parent.propagate = False
child.setLevel(logging.INFO)
child.propagate = True
h = logging.StreamHandler(s)
parent.addHandler(h)
child.info("event")
print(s.getvalue().count("event"))
parent.removeHandler(h)
1
Why this result follows: Propagation routes a child record to an ancestor handler when that routing is configured.
7. Expose duplicate routing
Problem: Count one child event handled locally and again by its parent.
- The child handler writes the admitted record once.
- Propagation sends the same record to the parent handler, which writes it again.
import logging, io
s = io.StringIO()
parent = logging.getLogger("duplicate")
child = logging.getLogger("duplicate.child")
parent.setLevel(logging.INFO)
parent.propagate = False
child.setLevel(logging.INFO)
child.propagate = True
h1 = logging.StreamHandler(s)
h2 = logging.StreamHandler(s)
parent.addHandler(h1)
child.addHandler(h2)
child.info("event")
print(s.getvalue().count("event"))
parent.removeHandler(h1)
child.removeHandler(h2)
2
Why this result follows: Handlers at both levels can duplicate one propagated event in the same destination.
8. Stop propagation deliberately
Problem: Count a child event when propagation is disabled and a child handler exists.
- The child handler writes the event once.
- propagate=False prevents the record from reaching the parent handler.
import logging, io
s = io.StringIO()
parent = logging.getLogger("isolated")
child = logging.getLogger("isolated.child")
parent.setLevel(logging.INFO)
parent.propagate = False
child.setLevel(logging.INFO)
child.propagate = False
h1 = logging.StreamHandler(s)
h2 = logging.StreamHandler(s)
parent.addHandler(h1)
child.addHandler(h2)
child.info("event")
print(s.getvalue().count("event"))
parent.removeHandler(h1)
child.removeHandler(h2)
1
Why this result follows: Disabling propagation changes routing and requires a suitable local destination if needed.
9. Record an active exception
Problem: Capture a controlled message and exception type without matching the full traceback.
- The active ValueError is recorded by logger.exception inside the handler.
- The captured text includes the stable message and exception type.
import logging, io
s = io.StringIO()
l = logging.getLogger("demo.exception")
l.setLevel(logging.ERROR)
l.propagate = False
h = logging.StreamHandler(s)
l.addHandler(h)
try:
raise ValueError("synthetic")
except ValueError:
l.exception("operation failed")
text = s.getvalue()
print("operation failed" in text, "ValueError" in text)
l.removeHandler(h)
True True
Why this result follows: Checking a message and type avoids depending on traceback paths or line numbers.
10. Attach exception information
Problem: Record a synthetic lookup error using error with exc_info enabled.
- The handler runs while KeyError is active.
- The captured record includes the controlled message and exception type.
import logging, io
s = io.StringIO()
l = logging.getLogger("demo.excinfo")
l.setLevel(logging.ERROR)
l.propagate = False
h = logging.StreamHandler(s)
l.addHandler(h)
try:
raise KeyError("x")
except KeyError:
l.error("lookup failed", exc_info=True)
text = s.getvalue()
print("lookup failed" in text, "KeyError" in text)
l.removeHandler(h)
True True
Why this result follows: The exc_info option attaches active exception information to the emitted error record.
11. Add a synthetic correlation field
Problem: Attach a fixed request identifier to an in-memory log record.
- The extra mapping adds request_id with value r1 to the record.
- The formatter writes that field followed by done.
import logging, io
s = io.StringIO()
l = logging.getLogger("demo.fields")
l.setLevel(logging.INFO)
l.propagate = False
h = logging.StreamHandler(s)
h.setFormatter(logging.Formatter("%(request_id)s:%(message)s"))
l.addHandler(h)
l.info("done", extra={"request_id": "r1"})
print(s.getvalue().strip())
l.removeHandler(h)
r1:done
Why this result follows: Explicit record context can support correlation when its field contract is defined.
12. Check a redacted marker
Problem: Log a redacted placeholder and verify a synthetic secret marker is absent.
- The logging call passes the placeholder rather than the marker.
- The captured stream does not contain SYNTHETIC_SECRET.
import logging, io
s = io.StringIO()
l = logging.getLogger("demo.redact")
l.setLevel(logging.INFO)
l.propagate = False
h = logging.StreamHandler(s)
l.addHandler(h)
secret = "SYNTHETIC_SECRET"
l.info("token=%s", "[redacted]")
print(secret not in s.getvalue())
l.removeHandler(h)
True
Why this result follows: Redaction before the handler prevents this fixture’s secret marker from reaching its destination.
13. Remove a test handler
Problem: Verify that an isolated handler no longer receives events after removal.
- The first event is written while the handler is attached.
- The handler is removed before the second event, so the stream contains only first.
import logging, io
s = io.StringIO()
l = logging.getLogger("demo.remove")
l.setLevel(logging.INFO)
l.propagate = False
h = logging.StreamHandler(s)
l.addHandler(h)
l.info("first")
l.removeHandler(h)
l.info("second")
print(s.getvalue().strip())
first
Why this result follows: Removing fixture handlers prevents later records from reaching that isolated test destination unexpectedly.
14. Filter selected records
Problem: Apply a synthetic handler filter that keeps only one fixed message.
- The filter rejects the message drop.
- It accepts keep, which the handler then writes to the captured stream.
import logging, io
s = io.StringIO()
l = logging.getLogger("demo.filter")
l.setLevel(logging.INFO)
l.propagate = False
h = logging.StreamHandler(s)
h.addFilter(lambda record: record.getMessage() == "keep")
l.addHandler(h)
l.info("drop")
l.info("keep")
print(s.getvalue().strip())
l.removeHandler(h)
keep
Why this result follows: A handler filter can make an explicit routing decision for each record.
15. Check a warning marker
Problem: Capture a warning and test for its controlled diagnostic phrase.
- The warning meets the logger threshold.
- The handler writes the phrase, so the membership check is true.
import logging, io
s = io.StringIO()
l = logging.getLogger("demo.warning")
l.setLevel(logging.WARNING)
l.propagate = False
h = logging.StreamHandler(s)
l.addHandler(h)
l.warning("limit reached")
print("limit reached" in s.getvalue())
l.removeHandler(h)
True
Why this result follows: A stable message fragment can be tested without depending on unrelated formatting.
16. Observe a disabled logger
Problem: Check that a disabled synthetic logger does not emit its informational event.
- The logger is explicitly disabled before the call.
- The stream remains empty, and the example restores the logger state.
import logging, io
s = io.StringIO()
l = logging.getLogger("demo.disabled")
l.setLevel(logging.INFO)
l.propagate = False
h = logging.StreamHandler(s)
l.addHandler(h)
l.disabled = True
l.info("event")
print(s.getvalue() == "")
l.disabled = False
l.removeHandler(h)
True
Why this result follows: A disabled logger suppresses its events regardless of its attached test handler.
17. Check before expensive diagnostics
Problem: Inspect whether a DEBUG event is enabled at an INFO logger threshold.
- DEBUG is below the configured INFO threshold.
- The logger’s isEnabledFor check therefore returns False for the DEBUG level.
import logging, io
s = io.StringIO()
l = logging.getLogger("demo.debug")
l.setLevel(logging.INFO)
l.propagate = False
h = logging.StreamHandler(s)
l.addHandler(h)
print(l.isEnabledFor(logging.DEBUG))
l.removeHandler(h)
False
Why this result follows: An enabled-level check can guard expensive diagnostic preparation when that preparation is appropriate.
18. Count distinct events
Problem: Capture two synthetic messages and inspect their order in one handler.
- The logger emits one and then two to the same stream.
- splitlines returns the two messages in their emitted order.
import logging, io
s = io.StringIO()
l = logging.getLogger("demo.two")
l.setLevel(logging.INFO)
l.propagate = False
h = logging.StreamHandler(s)
l.addHandler(h)
l.info("one")
l.info("two")
print(s.getvalue().splitlines())
l.removeHandler(h)
['one', 'two']
Why this result follows: An isolated capture can verify record count and order for a deterministic fixture.
19. Inherit an effective level
Problem: Inspect a child logger whose level delegates to its warning-level parent.
- The child is set to NOTSET, so it looks to its ancestors for an effective level.
- Its parent supplies WARNING, making the comparison true.
import logging
parent = logging.getLogger("levels")
child = logging.getLogger("levels.child")
parent.setLevel(logging.WARNING)
child.setLevel(logging.NOTSET)
print(child.getEffectiveLevel() == logging.WARNING)
True
Why this result follows: A logger without its own level can inherit an effective threshold from an ancestor.
20. Log and propagate separately
Problem: Record a synthetic exception and then deliberately re-raise it to the caller.
- The inner handler records the controlled message with exception information.
- The explicit raise propagates ValueError to the outer handler.
import logging, io
s = io.StringIO()
l = logging.getLogger("demo.errorflow")
l.setLevel(logging.ERROR)
l.propagate = False
h = logging.StreamHandler(s)
l.addHandler(h)
try:
try: raise ValueError("bad")
except ValueError:
l.exception("failed")
raise
except ValueError:
print("failed" in s.getvalue(), "propagated")
l.removeHandler(h)
True propagated
Why this result follows: Logging an exception and deciding whether it propagates are separate control-flow operations.
Common errors and fixes
An event is missing
- Why it happens
- A level or handler filters the record.
- How to fix it
- Inspect effective levels and destination.
- Prevent it next time
- Test configuration in the actual entry point.
A message appears twice
- Why it happens
- Handlers receive the event at multiple hierarchy levels.
- How to fix it
- Adjust handler placement or propagation deliberately.
- Prevent it next time
- Document who configures output handlers.
Sensitive values appear in logs
- Why it happens
- The event included a complete input object.
- How to fix it
- Remove sensitive fields and follow the applicable response process.
- Prevent it next time
- Use synthetic tests and a minimal event schema.
20 practice exercises
1. Why might a child logger and its parent duplicate a message?
Show hint
Trace the record through both the child and ancestor handlers.
Show worked solution
With propagation enabled, the child record reaches the parent handler as well as a handler attached directly to the child. Review handler placement before changing propagation.
With propagation enabled, a child record can reach both its own handler and a parent handler. If both write the same destination, the event appears twice. Review handler placement and intended routing before changing propagation.
Check your solution
- The child handler handles the event
- The parent handler also handles the propagated record
2. How can a test confirm that an exception was recorded without matching a complete traceback?
Show hint
Capture a controlled message and exception type instead of the complete traceback.
Show worked solution
Capture the handler output and check for a controlled message and exception type. This avoids dependence on line numbers or machine-specific paths.
Raise a known synthetic exception inside a handler, log it with exception information, and capture the handler output. Check a stable message and exception type without matching line numbers or machine-specific paths.
Check your solution
- The controlled message is present
- The exception type is present without requiring an exact traceback
3. A logger at WARNING receives INFO "low" and WARNING "high". Which message reaches its handler?
Show hint
The logger discards records below its effective level.
Show worked solution
The INFO message is below WARNING and is discarded. The WARNING message meets the threshold and reaches the handler, subject to the handler’s own level and filters. In this simple fixture, high is displayed.
Check your solution
- INFO low is discarded
- WARNING high reaches the handler
4. A logger admits DEBUG but its handler accepts ERROR. What happens to a WARNING event?
Show hint
Logger and handler thresholds are separate.
Show worked solution
The logger admits the WARNING record, but the handler’s ERROR threshold discards it. A test must consider both levels before concluding that a record should appear at that destination. Check the result against the documented logging policy.
Check your solution
- The logger admits WARNING
- The handler does not emit it
5. A child logger has a handler and propagates to a parent handler writing the same stream. Why can one event appear twice?
Show hint
Trace the record through both handler locations.
Show worked solution
The child handler writes the record once. With propagation enabled, the record reaches the parent handler, which writes it again. Review handler placement before changing propagation so intended destinations are not lost.
Check your solution
- The child handler writes once
- The parent handler writes the propagated record again
6. A child logger has propagate=False and one local handler. How many times does that handler receive one event?
Show hint
The event is handled locally but is not sent to ancestors.
Show worked solution
The local handler receives the event once if levels and filters admit it. The parent handler does not receive it through propagation. Ensure the local destination is appropriate before disabling ancestor routing.
Check your solution
- The local handler receives one record
- The parent does not receive it through propagation
7. Describe a test for a captured exception without matching its full traceback or machine-specific paths.
Show hint
Check a controlled message and exception type in a synthetic stream.
Show worked solution
Raise a known exception inside a handler, log it with logger.exception, and capture the handler output. Assert that a stable message and the exception type appear, without matching line numbers or absolute paths.
Check your solution
- The controlled message is present
- The exception type is present
8. Explain whether logger.exception automatically decides whether the caught exception propagates to the caller.
Show hint
Logging and control flow are separate operations.
Show worked solution
logger.exception records the active exception information, but the handler’s subsequent code determines whether it is re-raised, translated, or handled. Test the logging outcome and the intended propagation behavior independently. Check the result against the documented logging policy.
Check your solution
- The exception is recorded
- Propagation follows explicit control flow
9. A logger uses "count=%s" with argument 4. State the formatted message and a performance caveat.
Show hint
The argument fills the template when the record is formatted.
Show worked solution
The message is count=4. Parameterized formatting does not defer evaluation of an expensive expression passed as the argument; guard costly preparation when appropriate and measure its actual impact. Check the result against the documented logging policy.
Check your solution
- The formatted message is count=4
- Argument expressions are evaluated before the call
10. A synthetic secret marker must not reach a handler. Describe a focused redaction test.
Show hint
Capture the destination and assert the marker is absent.
Show worked solution
Send only a redacted placeholder to an isolated in-memory handler and inspect its captured text. Assert that the synthetic secret marker is absent from each destination covered by the fixture; test other real paths separately.
Check your solution
- The marker is absent from captured output
- The placeholder or safe message is present
11. Why should a reusable library normally avoid configuring global handlers during import?
Show hint
The application should control logging destinations and policy.
Show worked solution
Import-time global configuration can surprise callers, duplicate handlers, or alter unrelated logging. A library can obtain a named logger, while the application configures handlers, levels, and destinations deliberately. Check the result against the documented logging policy.
Check your solution
- Import does not unexpectedly configure global logging
- The application owns handler configuration
12. A test attaches a StreamHandler to a named logger. What cleanup should it perform?
Show hint
Avoid leaving logger state that affects later tests.
Show worked solution
Remove the handler after the test and restore any changed level or propagation settings when the logger may be reused. A self-contained fixture prevents later events from reaching the previous test’s stream unexpectedly.
Check your solution
- The handler is removed
- Changed logger state is restored
13. A child logger is NOTSET and its parent is WARNING. What effective level does the child use?
Show hint
A logger without its own level searches ancestors.
Show worked solution
The child inherits WARNING as its effective level from the parent in this configuration. An INFO event is below that threshold, while a WARNING event is admitted before handler-level filtering.
Check your solution
- The effective level is WARNING
- INFO is below the threshold
14. A logger is set to INFO. What does isEnabledFor(DEBUG) return and why might it be useful?
Show hint
DEBUG is below INFO.
Show worked solution
isEnabledFor(logging.DEBUG) returns False for this configuration. A caller can use the check to avoid preparing genuinely expensive debug-only data, while keeping ordinary logging calls straightforward. Check the result against the documented logging policy.
Check your solution
- The result is False
- The check can guard expensive preparation
15. Describe how a handler filter that accepts only "keep" treats "drop" and "keep" records.
Show hint
A filter makes a decision for each record.
Show worked solution
The filter rejects the record whose message is "drop" and accepts the record whose message is "keep". With one isolated handler, only keep appears in its captured stream. Check the result against the documented logging policy.
Check your solution
- drop is absent
- keep appears once
16. A named logger is disabled before an INFO call. What should an isolated stream contain?
Show hint
A disabled logger suppresses its events.
Show worked solution
The stream should remain empty for that call. Restore the disabled state and remove the handler after the test so the fixture does not alter later logging behavior. Check the result against the documented logging policy.
Check your solution
- The stream is empty
- Logger state is restored
17. Two messages "one" and "two" are emitted to one in-memory handler. What should the captured lines be?
Show hint
Check both the count and the order.
Show worked solution
With a simple message-only formatter, splitlines() should return ["one", "two"]. This verifies two deterministic records in the intended order for the fixture, without writing a real log file. Check the result against the documented logging policy.
Check your solution
- There are two lines
- The order is one then two
18. Explain why propagate=False is not automatically a complete fix for duplicate logging.
Show hint
It changes routing to all ancestor handlers.
Show worked solution
Disabling propagation stops the child record from reaching parent handlers, which can remove required destinations as well as duplicates. Review handler placement and ensure an appropriate local handler exists before choosing that configuration.
Check your solution
- Ancestor routing changes
- The intended destination is still present
19. A handler captures a synthetic request_id r1 and message done. State a useful formatted result.
Show hint
Use record fields in an explicit formatter.
Show worked solution
A formatter such as "%(request_id)s:%(message)s" produces r1:done when extra supplies request_id="r1". Document the field contract and avoid using sensitive identifiers without an appropriate policy. Check the result against the documented logging policy.
Check your solution
- The formatted result is r1:done
- The correlation field policy is explicit
20. Explain what a passing in-memory logging fixture does and does not establish about production logs.
Show hint
Separate local routing behavior from deployment properties.
Show worked solution
The fixture can verify configured levels, routing, messages, and cleanup for its synthetic logger. It does not prove production delivery, retention, confidentiality, or access controls; test those in the actual deployment environment.
Check your solution
- The local fixture behavior is verified
- Production delivery and access require separate evidence
Key takeaways
- Applications own output configuration; libraries use named loggers.
- Verify diagnostic usefulness without exposing sensitive input.
- Child and parent handlers can duplicate a propagated record.
- Logger thresholds and handler thresholds are separate filters.
- Logging an exception does not itself determine whether the exception propagates.