fix(logging): restore handlers and formatters on uninstrument - #4982
fix(logging): restore handlers and formatters on uninstrument#4982sidsri14 wants to merge 2 commits into
Conversation
When LoggingInstrumentor.instrument(set_logging_format=True) is called, basicConfig adds or configures root handlers with a format string interpolating %(otelTraceID)s, %(otelSpanID)s, etc. During _uninstrument, the log record factory is restored to the old factory, so subsequent log records no longer contain otelTraceID. However, because the format string remained in place on root handlers, any record logged after uninstrument failed to format with a KeyError/ValueError. This captures the root level, handlers, and formatters before basicConfig and restores them upon _uninstrument.
|
Nice, this is a real gap (#4949). Two things I noticed: The cleanup removes more than it should — The formatter-restore test also doesn't exercise the restore: |
Addresses review feedback on open-telemetry#4982: the previous approach snapshotted all root handlers before basicConfig and dropped anything not in that set on uninstrument, silently removing handlers the application added while instrumented. Record only the handlers basicConfig actually added and remove exactly those. Rewrite the test to start from a handler-less root so basicConfig runs, and verify the app-added handler survives uninstrument while the root level is restored. Assisted-by: Claude Sonnet 4.6
Description
Fixes #4949.
When
LoggingInstrumentor().instrument(set_logging_format=True)is called,logging.basicConfig()configures or attaches root handlers with a format string interpolating OpenTelemetry trace context fields (%(otelTraceID)s,%(otelSpanID)s, etc.).During
_uninstrument(), the log record factory was restored to_old_factory, but the format string remained active on the root logger's handlers. Because newly createdLogRecordinstances no longer carriedotelTraceID, any record logged afteruninstrument()failed to format, causing silent log dropping andValueError: Formatting field not found in record: 'otelTraceID'viaHandler.handleError.Changes
_instrument(): Whenset_logging_formatis active, capture the pre-instrumentation root logger state (level,handlers, and existingformatters)._uninstrument(): Restore the root logger level, restore previous formatters on pre-existing handlers, and remove any handlers added during instrumentation.tests/test_logging.py: Added unit tests verifying:uninstrument()succeeds withoutKeyError/ValueErroron formatting.Type of change
How Has This Been Tested?
pytest instrumentation/opentelemetry-instrumentation-logging/tests: all 73 tests passed.Checklist: