chore: Replace print statements with logger#2452
Conversation
WalkthroughQuery request error paths and mirror-node discovery now use module-level logging instead of direct console output, while preserving re-raises and fallback results. New unit tests verify logger names, levels, exception information, and removal of direct traceback printing. ChangesStructured error logging
Estimated code review effort: 2 (Simple) | ~10 minutes 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
📋 Issue PlannerLet us write the prompt for your AI agent so you can ship faster (with fewer bugs). View plan for ticket: ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
6afbe47 to
9aba0b3
Compare
6f0fa5d to
2e7e5ac
Compare
manishdait
left a comment
There was a problem hiding this comment.
@iron-prog, thanks for the PR, just a small change request
| print(f"Error fetching nodes from mirror node API: {e}") | ||
| logger.error("Error fetching nodes from mirror node API: %s", e) | ||
| return [] | ||
| except (ValueError, KeyError, TypeError, IndexError, AttributeError) as e: |
There was a problem hiding this comment.
I think we can just fall back to a generic Exception here instead of listing all the possible exception types
There was a problem hiding this comment.
This problem comes from NodeAddress._from_dict, where missing keys pass None thus you get the variety of type erorrs/attribute errors/etc
So i think we should look at is improve none handling, which maybe should be a different PR what do you think @manishdait ?
| print(f"Error fetching nodes from mirror node API: {e}") | ||
| logger.error("Error fetching nodes from mirror node API: %s", e) | ||
| return [] | ||
| except (ValueError, KeyError, TypeError, IndexError, AttributeError) as e: |
There was a problem hiding this comment.
This problem comes from NodeAddress._from_dict, where missing keys pass None thus you get the variety of type erorrs/attribute errors/etc
So i think we should look at is improve none handling, which maybe should be a different PR what do you think @manishdait ?
Signed-off-by: iron-prog <dt915725@gmail.com>
Signed-off-by: iron-prog <dt915725@gmail.com>
- Replace remaining logging.error(...) (root logger) with logger.error() - Add exc_info=True to file_contents_query.py for traceback parity - Strengthen tests: seed valid IDs, assert emitting logger identity (record.name == module), assert traceback is attached (record.exc_info) Signed-off-by: iron-prog <dt915725@gmail.com>
Signed-off-by: iron-prog <dt915725@gmail.com>
2e7e5ac to
24472d2
Compare
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/hiero_sdk_python/query/token_info_query.py (1)
69-70: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winRestore required token-ID validation.
if self.token_idnow allowsNone, so_make_request()silently builds a request with an empty/default token instead of raising the documentedValueError. Restore the guard and serialize only after validation.Suggested fix
try: + if self.token_id is None: + raise ValueError("Token ID must be set before making the request.") query_header = self._make_request_header() token_info_query = token_get_info_pb2.TokenGetInfoQuery() token_info_query.header.CopyFrom(query_header) - if self.token_id: - token_info_query.token.CopyFrom(self.token_id._to_proto()) + token_info_query.token.CopyFrom(self.token_id._to_proto())Add a regression test for
TokenInfoQuery()._make_request()without a token ID.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: be976864-47ab-41c2-be81-e9bcded72eb1
📒 Files selected for processing (15)
src/hiero_sdk_python/account/account_records_query.pysrc/hiero_sdk_python/client/network.pysrc/hiero_sdk_python/contract/contract_bytecode_query.pysrc/hiero_sdk_python/contract/contract_call_query.pysrc/hiero_sdk_python/contract/contract_info_query.pysrc/hiero_sdk_python/file/file_contents_query.pysrc/hiero_sdk_python/file/file_info_query.pysrc/hiero_sdk_python/query/account_balance_query.pysrc/hiero_sdk_python/query/account_info_query.pysrc/hiero_sdk_python/query/token_info_query.pysrc/hiero_sdk_python/query/token_nft_info_query.pysrc/hiero_sdk_python/query/topic_info_query.pysrc/hiero_sdk_python/query/transaction_get_receipt_query.pysrc/hiero_sdk_python/schedule/schedule_info_query.pytests/unit/query_error_logging_test.py
| except requests.RequestException as e: | ||
| print(f"Error fetching nodes from mirror node API: {e}") | ||
| logger.error("Error fetching nodes from mirror node API: %s", e) | ||
| return [] |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
MINOR — Preserve traceback context for mirror-node request failures.
This branch logs only str(e), so the structured record has no exc_info, unlike the parsing branch and query handlers. Add exc_info=True (or use logger.exception) and assert traceback retention in the request-failure test.
| source = inspect.getsource(Network._fetch_nodes_from_mirror_node) | ||
| assert "print(" not in source |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Assert that network code does not call traceback.print_exc().
These checks only search for "print("; that does not match traceback.print_exc(), so direct traceback output could be reintroduced while the tests remain green.
Suggested assertion
assert "print(" not in source
+ assert "traceback.print_exc()" not in source, (
+ "Network._fetch_nodes_from_mirror_node still calls traceback.print_exc()"
+ )Also applies to: 144-145, 173-174
| assert result == [] | ||
| matching = [ | ||
| record | ||
| for record in caplog.records | ||
| if record.levelno == logging.WARNING and "No known mirror node URL" in record.message | ||
| ] | ||
| assert matching | ||
| assert matching[0].name == Network.__module__ |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Add diagnostic messages to mirror-node assertions.
The new tests use bare assertions for results, matching log records, and logger names, making failures ambiguous. Add descriptive messages to each assertion.
As per path instructions, unit tests must provide useful error messages when they fail.
Also applies to: 161-168, 195-202
Source: Path instructions
| if record.levelno == logging.ERROR and "Error parsing mirror node API response" in record.message | ||
| ] | ||
| assert matching | ||
| assert matching[0].name == Network.__module__ |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Assert traceback retention for malformed responses.
This test exercises the parsing branch that uses exc_info=True, but it only checks the log message and logger name. Add an assertion that matching[0].exc_info is not None so traceback loss is detected.
Description:
Replace
print()andtraceback.print_exc()with structured logging across query and network modules.print()/traceback.print_exc()withlogger.error(..., exc_info=True)orlogger.warning(...)tracebackimportsprint()calls remain, logs use the correct module logger, and tracebacks are preservedRelated issue(s):
Fixes #2403
Notes for reviewer:
print(...)examples were intentionally left unchangedTransactionGetReceiptQueryuses a different mock target because it builds its header inlineChecklist