Add structured logging with PLC connection context#688
Merged
Conversation
New snap7.log module with:
- PLCLoggerAdapter: injects plc_host, plc_rack, plc_slot, plc_protocol
into every log record and prefixes messages with [host R{rack}/S{slot}]
- OperationLogger: context manager that logs operation timing at DEBUG
level (e.g. "db_read db=1 start=0 size=4 (2.3ms)")
- JSONFormatter: single-line JSON output for structured log aggregation
(ELK, Datadog, etc.)
Integration:
- Client.__init__ creates self.logger as PLCLoggerAdapter
- Client.connect updates context with host/rack/slot/protocol
- db_read uses OperationLogger for timing
Backward compatible: standard logging.getLogger("snap7") still works.
The adapter adds context fields without changing the logger hierarchy.
Closes #618.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
logging.LoggerAdapter[logging.Logger] requires Python 3.11+. Use the non-generic form for 3.10 compatibility. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
New
snap7.logmodule with structured logging support for multi-PLC environments.PLCLoggerAdapter— wraps the standard logger and injects PLC context:OperationLogger— context manager that logs operation timing at DEBUG:JSONFormatter— single-line JSON output for log aggregation (ELK, Datadog):{"ts":"2024-01-15T10:30:00","level":"INFO","logger":"snap7.client", "msg":"Connected","plc_host":"192.168.1.10","plc_rack":0,"plc_slot":1}Fully backward compatible — standard
logging.getLogger("snap7")still works unchanged.Closes #618.
Test plan
🤖 Generated with Claude Code