[PORT] First-class logging module + warn_once (TS→Py)
⚠️ Filed by Strandly as part of the #2498 parity audit. Source feature verified merged + unit-tested in
strands-ts. Agent-produced — this one needs a design decision, not a mechanical port (see gotchas). (Noportlabel yet — a maintainer should add it.)
Parent: #2498
Source SDK
strands-ts
Target SDK
strands-py
Related Files
strands-ts/src/logging/index.ts
strands-ts/src/logging/logger.ts
strands-ts/src/logging/types.ts
strands-ts/src/logging/warn-once.ts
strands-ts/src/logging/__tests__/logger.test.ts
strands-ts/src/logging/__tests__/warn-once.test.ts
site/src/content/docs/user-guide/observability-evaluation/logs.mdx
site/src/content/docs/user-guide/observability-evaluation/logs.ts
What needs to be migrated
TS ships a small injectable-logger façade; Python has no logging module (uses stdlib logging.getLogger(__name__) everywhere).
Loggerinterface (types.ts:10): variadicdebug/info/warn/error(...args).logger(logger.ts:25): a mutable module-global singleton imported by ~43 source files.configureLogging(customLogger)(logger.ts:44): swaps the global (public export).defaultLogger(logger.ts:15):debug/infono-op;warn→console.warn,error→console.error.warnOnce(logger, msg)(warn-once.ts:15): process-globalSet<string>dedup, emitwarnat most once per message. Used at 8 call sites (conversation-manager, model providers, graph, swarm, goal plugin). Not publicly exported.
Python landing points
warn_onceis the clearly portable piece — Python has the same "unbounded execution" / "default model" nudges that would benefit (mirror the TS call sites inmultiagent/,models/,conversation_manager.py). Python's conversation manager currently uses a per-instance boolean flag instead of a process-global once.- 81
getLogger(__name__)call sites instrands-py/, all children of the"strands"root logger (perlogs.mdx). A faithful port must not disturb this hierarchy.
Gotchas / open questions (need maintainer input)
- The injectable-global-logger pattern is a TS-ism that fights Python idiom. Python's established approach (and this SDK's) is per-module
getLogger(__name__)configured by the application. Porting the global singleton verbatim would rewrite 81 call sites and abandon the standard hierarchy. Recommended defensible scope: keepgetLogger(__name__), add onlywarn_once. Confirm before doing more. warnvswarning. Stdlib islogging.Logger.warning(warndeprecated) — aLoggerProtocol requiringwarnwouldn't be satisfied by a stdlib logger. Usewarningor an adapter.- Variadic args differ. TS
warn(...args)concatenates (console-style); Pythonlogger.warning(msg, *args)is printf/%-style. Don't map...args→*argsnaively.warn_once(logger, msg)is single-message → ports cleanly.
Completeness of source (strands-ts)
- Merged: ✅ · Unit tests: ✅ (
logger.test.ts,warn-once.test.ts) · Integ: ❌ none. - Docs: ✅ for
configureLogging/Logger(logs.mdx+logs.ts); ⚠️warnOnceis undocumented / not a public export.
Confirmation
- [x] The change is complete in the source SDK (merged + unit-tested); every related artifact is listed above.
@strandly-the-agent can you look into how the logger behaves for Typsescript and compose a design document on how to implement in python?
TL;DR — don't port the TS logging module; the design decision is already made in strands-py/AGENTS.md:78-82, and Python stdlib already gives us every behaviour the TS module adds. What's left is a small convergence PR.
- TS behaviour (verified @
1556ede): a mutable module-globallogger(63 importers) behind a 4-method console-styleLoggerinterface, swapped viaconfigureLogging; default = warn/error to console, debug/info no-op.warnOnceis a process-globalSet<string>keyed on the message, 16 call sites, not exported — and it already costs TS test isolation (vi.mockin 6 test files) and a duplicated copy inharness-ts/src/logging.ts. - Python equivalents already exist: stdlib's
lastResorthandler gives the same default (WARNING+ to stderr, nothing else — verified); handler injection onlogging.getLogger("strands")isconfigureLogging;warnings.warndedupes once per call site + message (verified, incl. pytest resetting it per test). 15 of 16warnOncesites are developer-facing config nudges, which is exactly thewarnings.warnaudience. - Proposed PR: convert the two Python sites that drifted —
multiagent/graph.py:499(logger.warningon everybuild()) andmodels/model.py:339-348(logger.warning+ hand-rolled_utilization_limit_warnedflag) — towarnings.warn(..., stacklevel=N); one docs paragraph onwarnings/captureWarningsinlogs.mdx; one parity line in rootAGENTS.md(warnOnce↔warnings.warn) so #2498 stops re-filing this. - Not recommended: a faithful port (103 call sites, breaks the documented
"strands"logger hierarchy,warn≠warning) or an internalwarn_once(contradictsAGENTS.md:82; no operational site needs it today).
Open question for you: agree warn_once should not exist in Python, and close this with the convergence PR? Happy to open that PR if so.
Full design doc (TS behaviour, site-by-site mapping, options, concrete change list)
Recommendation
Do not port the module. Python's stdlib already provides every behaviour the TS module adds, and
strands-py/AGENTS.md:78-82 already settles the warn_once question ("if you catch yourself building a
process-global warn-once set over the logger, you almost certainly want warnings.warn"). What remains
is a small convergence PR: two Python call sites that drifted from that rule, one docs paragraph, and
one line in the root AGENTS.md so the parity audit stops re-filing this.
1. How the TS logger behaves
| Piece | Where | Behaviour |
|---|---|---|
Logger interface |
strands-ts/src/logging/types.ts:10 |
debug/info/warn/error(...args: unknown[]) — console-style variadic, args are passed through, not formatted |
logger |
logger.ts:25 |
mutable module-global (export let), imported by 63 source files |
configureLogging(l) |
logger.ts:44 |
reassigns the global; the only public entry point (index.ts:312-313 exports configureLogging + Logger type) |
defaultLogger |
logger.ts:15 |
debug/info no-op; warn → console.warn; error → console.error |
warnOnce(logger, msg) |
warn-once.ts:15 |
process-global Set<string>, dedupe key = full message string; internal, not exported |
Level usage in strands-ts/src (non-test): debug 90, info 8, warn 190, error 12.
warnOnce has 16 call sites today (the issue body's "8 incl. conversation-manager" is stale):
models/anthropic.ts:159,163, models/bedrock.ts:441,634, models/google/model.ts:96, models/model.ts:392,
models/openai/cache.ts:94,111, models/openai/model.ts:87, models/vercel.ts:265,277,350,389,
multiagent/graph.ts:174, multiagent/swarm.ts:168, vended-plugins/goal/plugin.ts:269.
Every one of them is a developer-facing usage nudge (default modelId/maxTokens, unsupported
cacheConfig/ttl/strategy, no maxSteps/timeout, contextWindowLimit unset) except
bedrock.ts:634 (CountTokens AccessDeniedException → heuristic fallback), which is operational and is
also guarded by SKIP_COUNT_TOKENS_MODELS, so the once-set is redundant there.
Costs the design already pays in TS — worth not importing:
- Test isolation. The global
Setleaks across tests, so 6 test filesvi.mock('../../logging/warn-once.js')(e.g.models/__tests__/bedrock.test.ts:152) and assert on the mock rather than the log. - Message-as-key. Dropping a
field=<value>from a message collapses every distinct value into one warning (seen in review on #4055). - Not exported, so duplicated.
harness-ts/src/logging.tscarries its own copy oflogger+warnOnce+ aresetWarnOnce()for tests;strands-ts/src/a2a/logging.tshand-rolls a separate_loggedboolean.
2. What Python already has
- 103
logging.getLogger(__name__)sites, all under thestrandsroot logger (documented insite/.../logs.mdx, Python tab). Levels:debug398,info25,warning183,error21,exception28. - 40
warnings.warn(...)sites, split fromlogger.warningby audience perstrands-py/AGENTS.md:78-82(reference impl:models/_validation.pyusesstacklevel=4). - Default behaviour already matches TS with zero code. With no handler configured, stdlib's
lastResorthandler writes WARNING+ to stderr and drops DEBUG/INFO — verified on 3.13:logger.debug/infosilent,logger.warning/errorprinted. That isdefaultLogger. - Injection already exists.
configureLogging(pino)≡logging.getLogger("strands").addHandler(...); structlog/loguru users attach an intercept handler. Standard Python, already in the docs. - Dedupe already exists for the right audience.
warnings.warnunder the default filter emits once per(message, category, module, lineno). Verified: a loop calling awarnings.warn(f"model_id=<{id}> …", stacklevel=2)helper 3× forathen 3× forbprints exactly two lines — same per-distinct-message semantics aswarnOnce, but scoped to the user's call site (better: it tells them which line), with no global state. pytest resets the registry per test (verified: two tests bothpytest.warnson the same line, both pass) — so none of thevi.mockceremony. Operators who want these in logs anyway calllogging.captureWarnings(True)→py.warningslogger.
TS warnOnce sites mapped onto Python
| TS site | Python today | Verdict |
|---|---|---|
default modelId (bedrock / anthropic / openai / gemini) |
models/bedrock.py:1793 warnings.warn(…, stacklevel=2) |
✅ already correct |
openai ttl not a retention value (cache.ts:111) |
models/_openai_cache.py:69 warnings.warn(…, stacklevel=4) |
✅ |
goal plugin unbounded (goal/plugin.ts:269) |
vended_plugins/goal/plugin.py:272 warnings.warn(…, stacklevel=2) |
✅ |
bedrock CountTokens AccessDenied (bedrock.ts:634) |
models/bedrock.py:1309 logger.warning + _SKIP_COUNT_TOKENS_MODELS (once per model) |
✅ operational → logger is the right audience |
graph unbounded (graph.ts:174) |
multiagent/graph.py:499 logger.warning(...) — fires on every build(), no dedupe, wrong audience |
❌ fix |
contextWindowLimit default (model.ts:392) |
models/model.py:339-348 logger.warning guarded by a per-instance _utilization_limit_warned flag; 4 tests poke the flag |
❌ fix |
unknown cache strategy (vercel.ts:277) |
models/anthropic.py:426 logger.warning inside request formatting — likely fires per request |
⚠️ implementer to confirm, probably same fix |
swarm unbounded (swarm.ts:168) |
Python Swarm defaults are bounded (max_handoffs=20, max_iterations=20, execution_timeout=900) |
n/a |
anthropic default maxTokens, vercel cacheConfig |
Python max_tokens is Required[int]; no Vercel provider |
n/a |
3. Options considered
A. Faithful port — Logger Protocol + configure_logging() + a module-global logger.
Rejected. Rewrites 103 call sites; breaks every user who configures logging.getLogger("strands") as the
docs tell them to; a stdlib Logger has warning not warn so it would not even satisfy the Protocol;
TS variadic pass-through ≠ Python %s interpolation (ruff G enforces the latter). Nothing is gained —
handler injection is what stdlib is.
B. Internal strands/_logging.py::warn_once(logger, msg) only.
Rejected for now. Directly contradicts AGENTS.md:82; every candidate site is developer-facing, where
warnings.warn already dedupes without global state. Keep in reserve only if a genuinely operational
warning that repeats per request appears — none does today (the one operational case is already guarded).
C. No new module; converge the drifted sites + docs. ← recommended.
4. Proposed change (option C)
One small PR in strands-py/ (+ docs):
multiagent/graph.py:499→warnings.warn("graph has no max_node_executions or execution_timeout; execution is unbounded", stacklevel=3)(GraphBuilder._validate_graph←build()← user, sostacklevel=3lands on the user'sbuild()line; the separateGraph._validate_graphat:711does not warn). Message text mirrorsgraph.ts:174per the parity rule.models/model.py:339-348→warnings.warn(f"context_window_limit not set on model, using default of {DEFAULT_CONTEXT_WINDOW_LIMIT} for utilization estimate | set context_window_limit in your model config for accurate results", stacklevel=2); delete the_utilization_limit_warnedattribute. Noteestimate_utilizationis called from SDK internals (conversation managers), sostacklevelcannot reach user code — dedupe still works (per internal call site), which is the goal. Updatetests/strands/models/test_model.py:675and the three flag-resets intests/strands/agent/test_conversation_manager.py:829,test_summarizing_conversation_manager.py:874,939topytest.warns(UserWarning, match=...)/warnings.catch_warningsas appropriate.models/anthropic.py:426— if it fires per request, same treatment with the rightstacklevel.- Docs
logs.mdx, Python tab — add a short "Usage warnings" note: config/usage nudges are emitted via Pythonwarnings(not the logger); control with-W/PYTHONWARNINGS(e.g.-W error::UserWarningin CI);logging.captureWarnings(True)routes them into thepy.warningslogger if you want them in log aggregation. - Root
AGENTS.mdparity section — one line: TSwarnOnce(logger, msg)↔ Pywarnings.warn(msg, stacklevel=N), so the #2498 audit has a recorded mapping and stops flagging this as a gap. - Tests:
pytest.warns(UserWarning, match="execution is unbounded")for graph; same for model default. No test for "second call does not warn" — that's stdlib behaviour, not ours.
5. Open questions for maintainers
- Agree
warn_onceshould not exist in Python (perAGENTS.md:82), and close #3152 with the convergence PR? - Should the issue be retitled from
[PORT]to reflect that it's a convergence/cleanup, or closed in favour of a new one?