Repository navigation
feat: add internal diagnostic log & console/file logging - #1479
Conversation
Introduce a new internal diagnostic logging module (swanlab.sdk.internal.pkg.log) with memory-buffered startup, RotatingFileHandler binding (bindfile), and reset semantics. Integrate console with the diagnostic log (console now mirrors output to the log when SWANLAB_DEBUG is enabled) and adjust imports to use internal.pkg.console. Enhance core client session to record HTTP request timings, trace IDs and write debug/error diagnostics via the new log module. Add unit tests for the log lifecycle and bindfile behavior and update test conftest to reset the diagnostic logger and client between tests.
Introduce DEBUG-driven HTTP request/response logging and tests. Added a DEBUG flag in swanlab.sdk.pkg.helper.env and updated SessionWithRetry to log request/response headers and bodies when DEBUG is enabled (with a 1000-char truncation and explicit markers). Console debug now checks helper.env.DEBUG instead of a local env var. Unit tests were added to cover successful responses, error responses (including original error body), and truncation behavior. Minor imports adjusted to use the shared helper.env.DEBUG.
Introduce format_body_preview to safely decode and truncate request/response bodies (handles bytes with utf-8 replace, returns empty for None, appends " ... (truncated)" when > max_len). Integrate it into SessionWithRetry debug logging to replace ad-hoc slicing and provide safer previews (including error-response logging). Update tests: add unit tests for format_body_preview, adapt DEBUG logging tests to assert formatted args and truncation behavior, and import the new helper.
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! 此拉取请求旨在显著提升 SwanLab SDK 的内部可观测性和调试能力。通过引入一个全新的、功能丰富的诊断日志模块,并将其与现有的控制台输出以及核心网络请求逻辑深度集成,开发者现在可以在 SWANLAB_DEBUG 模式下获得更详细、更持久的内部运行信息。这不仅有助于快速定位和解决问题,还能在不影响用户体验的前提下,提供强大的后台诊断支持。 Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
Change the function signature from `bytes | str | None` to `Optional[bytes | str]` for format_body_preview to standardize the typing annotation and improve readability. This is a type-only change with no behavioral impact.
Import typing.Union and replace PEP 604 style union (bytes | str) with Optional[Union[bytes, str]] in format_body_preview's type hint. This ensures the annotation is compatible with Python versions and tooling that don't support the X | Y union syntax.
Replace the private alias _log with log and make console handlers (info, warning, error, critical) forward messages to the internal logger only when helper.env.DEBUG is true. Debug logging still requires DEBUG (behavior unchanged except for the import). This avoids emitting duplicate/noisy logs in non-debug environments. (modified: swanlab/sdk/internal/pkg/console/__init__.py)
There was a problem hiding this comment.
Code Review
This PR introduces a well-designed internal diagnostic logging module, integrating it with the console and HTTP client, which is a great feature enhancement. While aspects like memory buffering, delayed binding, and enhanced HTTP session logging are commendable, a critical security concern has been identified. When SWANLAB_DEBUG is enabled, the current implementation logs sensitive information such as session tokens and potentially API keys in plain text to a log file. Furthermore, the log file is created with default system permissions, potentially allowing unauthorized access in multi-user environments. To address these risks, it is highly recommended to implement sanitization for sensitive headers and bodies before logging and to restrict log file permissions to the current user.
Add SecureRotatingFileHandler that enforces 0o600 file permissions when opening/creating the log file on POSIX systems (to reduce risk of credential leakage on shared clusters). Replace RotatingFileHandler with SecureRotatingFileHandler in bindfile. Add unit test (test_secure_file_permissions) to validate the generated debug.log has 0600 permissions on POSIX; import os/stat in tests. Windows behavior unchanged (permission enforcement skipped).
Add type annotations and small refactors to improve typing and clarity. In session.py, annotate request_retries_ctx as ContextVar[Optional[int]] and introduce local variables for request.body and response.text when formatting debug previews to avoid repeated property access. In console/__init__.py, import Any and annotate _to_plain_text(*args: Any) to make varargs typing explicit. These changes are purely local/clarity improvements to aid static checking and logging readability.
引入一个新的内部诊断日志模块(swanlab.sdk.internal.pkg.log),该模块具有内存缓冲启动功能、RotatingFileHandler绑定(bindfile)以及重置语义。
将控制台与诊断日志集成(当启用SWANLAB_DEBUG时,控制台输出将同步记录到日志中),并调整导入以使用internal.pkg.console。
增强核心客户端会话功能,以记录HTTP请求时间、跟踪ID,并通过新日志模块写入调试/错误诊断信息。新增针对日志生命周期和bindfile行为的单元测试,并更新测试配置(conftest),确保在测试间重置诊断日志记录器和客户端。
对于 SWANLAB_DEBUG 的效果如下,当 SWANLAB_DEBUG 开启(设置为
["true", "1", "yes", "on"]之一)时:for #1132