Skip to content

Add structured logging with PLC connection context#688

Merged
gijzelaerr merged 2 commits into
masterfrom
feature/structured-logging
Apr 15, 2026
Merged

Add structured logging with PLC connection context#688
gijzelaerr merged 2 commits into
masterfrom
feature/structured-logging

Conversation

@gijzelaerr
Copy link
Copy Markdown
Owner

Summary

New snap7.log module with structured logging support for multi-PLC environments.

PLCLoggerAdapter — wraps the standard logger and injects PLC context:

[192.168.1.10 R0/S1] Connected to 192.168.1.10:102 rack 0 slot 1
[192.168.1.10 R0/S1] db_read db=1 start=0 size=4 (2.3ms)

OperationLogger — context manager that logs operation timing at DEBUG:

with OperationLogger(self.logger, "db_read", db=1, start=0, size=4):
    data = self.read_area(...)

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

  • 8 new tests for PLCLoggerAdapter, OperationLogger, JSONFormatter
  • All 1433 existing tests pass
  • mypy and ruff clean

🤖 Generated with Claude Code

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>
@gijzelaerr gijzelaerr added this to the 4.0 milestone Apr 15, 2026
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>
@gijzelaerr gijzelaerr merged commit 5b73d7e into master Apr 15, 2026
39 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Structured logging with operation context

1 participant