Use this when Python scripts need proper logs.
Logging · Python Automation
Python logging uses the logging module with levels (DEBUG to CRITICAL), handlers and formatters, so automation writes timestamped logs to files or syslog instead of print statements.
1. Use the logging module, not print, for automation.
2. Levels and handlers.
3. Structured (JSON) logs for central systems.
4. Configure once at entry point.
5. Mask secrets.
code → logger → handlers → output
Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
Capture the concrete output, symptom, packet, log or counter before changing anything.
Step 1 Verification path Verify boundary
The negative fixture should deliberately exercise risks such as environment drift, implicit coercion, broad exception handling, blocking/async confusion, shell quoting/subprocess risks, partial writes and non-deterministic external APIs, choosing the cases most relevant to logger hierarchy/configuration, structured context/correlation, levels, exception tracebacks, redaction and distinguishing diagnostic logs from authoritative target state.
Step 2 Common mistakes Narrow the fault
printinstead of logging.
Evidence · 1 on this Topic
Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.
- Use the logging module, not print.
- Levels: DEBUG, INFO, WARNING, ERROR, CRITICAL.
- Handlers send logs to files or syslog.
python3 -c 'import logging; logging.basicConfig(level=logging.INFO); logging.info("ok")'— basic logging- Log format with timestamp and level — consistency
- No secrets in logs — security
ReferenceWhy it matters1 section · depth on demand
In depth
The logging module records what a script does with levels, timestamps and consistent formatting, and can send output to the console, files or a central log system. Unlike print, log levels can be raised or lowered without changing the code.
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
handlers=[logging.StreamHandler(), logging.FileHandler("deploy.log")],
)
log = logging.getLogger("deploy")
log.info("pushing config to %s", host)
log.debug("rendered config:\n%s", config)
try:
push(host)
except Exception:
log.exception("push failed for %s", host) # includes traceback
Never log passwords or tokens, use %s arguments instead of f-strings (formatting only happens if the message is emitted), and lower noisy libraries: logging.getLogger("paramiko").setLevel(logging.WARNING).
ReferenceImportant terms & boundaries1 section · depth on demand
Mechanics
The linked authority for bounded mechanics is Python Documentation — logging; documentation support is separate from observed lab/production Evidence.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
Authoritative/upstream documentation reviewed for bounded claims in Python Automation > Logging. Documentation verification only; this is not observed lab or production Evidence.
Basis: https://docs.python.org/3/library/logging.html · confidence 94%Deep reference
Healthy vs suspicious evidence
Output interpretation
For logger hierarchy/configuration, structured context/correlation, levels, exception tracebacks, redaction and distinguishing diagnostic logs from authoritative target state, prefer typed fields and stable IDs over human presentation text.