12.5 DrySister看妹子应用(第一版)——5.代码回顾,调整与日志类编写
复盘 DrySister 前四节核心架构,完成 Android Studio 3.0 工程升级、中文 URL 分段转码与 rebase 合并,并系统梳理 Log 五级规范、BuildConfig.DEBUG 日志工具类与 UncaughtExceptionHandler 崩溃日志采集。
学完这一章,你能够
- 复盘 DrySister 前四节核心架构,完成 Android Studio 3.0 工程升级、中文 URL 分段转码与 rebase 合并,并系统梳理 Log 五级规范、BuildConfig.DEBUG 日志工具类与 UncaughtExceptionHandler 崩溃日志采集。
前四节架构复盘与 Android Studio 3.0 迁移调整
在进入收尾发布前,先系统复盘前四节串联起的基础知识版图:第一节落实 Git 仓库分支规范与 `HttpURLConnection + Handler` 初始图片加载;第二节实现原生 `JSONObject/JSONArray` 解析与 `AsyncTask` 异步分页;第三节落地采样压缩、线程池、URL 摘要键与 `LruCache + DiskLruCache` 二级图片缓存;第四节补齐网络状态检测、`SQLiteOpenHelper` 建表、事务批量入库与离线分页读取。
随着开发环境从 AS 2.1.2 升级至 AS 3.0.1,新建分支 `fix_code_as3.0.1` 完成四项兼容性与体验调整:① 同步更新项目级 `build.gradle`、模块级 `build.gradle` 与 `gradle-wrapper.properties` 插件及 Gradle 版本;② 修复 `SisterApi.java` 中含中文路径的接口地址——`HttpURLConnection` 对未转码非 ASCII 路径易报错,需仅对中文路径段 `"福利"` 调用 `URLEncoder.encode("福利", "utf-8")` 转为 `%e7%a6%8f%e5%88%a9`(切忌对整条含 `http://` 和 `/` 的 URL 整体编码,否则协议头会被破坏,本站实验已做正反对照);③ 升级至 `compileSdkVersion`/`buildToolsVersion` 26+ 后 `findViewById` 已支持泛型推断,清理全部冗余强转;④ 为 `ImageView` 添加 `android:adjustViewBounds="true"` 使图片按原比例满宽自适应,并将按钮文案抽取至 `strings.xml`。改动完成后使用 `git rebase` 将特性提交线性变基至 `develop` 再推送并删除本地分支。
Android Log 五级规范、Live Templates 与 LogUtils 封装
调试日志治理是工程化底线,应杜绝随手滥用 `Log.e()` 或将敏感调试信息带入线上版本。Android Studio 可在 `Settings → Live Templates → AndroidLog` 勾选 `logd`、`loge`、`logt` 等快捷模板快速生成带方法名/类名的标准日志语句。五个标准日志级别职责明确:`Log.v`(Verbose,冗长细节,仅开发阶段使用)、`Log.d`(Debug,调试信息,运行时关闭)、`Log.i`(Info,关键运行状态,禁止充当普通调试输出)、`Log.w`(Warning,潜在异常警告)与 `Log.e`(Error,明确错误,优先排查)。在 `bug_log_catch` 分支编写 `LogUtils` 时,利用自动生成的 `BuildConfig.DEBUG` 布尔常量作为门控开关:Debug 构建正常打印,Release 构建自动静默,避免发布包泄露内部业务信息。
基于 Thread.UncaughtExceptionHandler 的本地崩溃日志采集
线上用户遇到未捕获异常崩溃时无法直连电脑查看 Logcat,除接入 Bugly/Firebase Crashlytics 等成熟平台外,理解原生崩溃采集机制同样关键:编写单例 `CrashHandler` 实现 `Thread.UncaughtExceptionHandler`,在 `DrySisterApp.onCreate()` 初始化时先通过 `Thread.getDefaultUncaughtExceptionHandler()` 保存系统默认处理器,再调用 `Thread.setDefaultUncaughtExceptionHandler(this)` 接管未捕获异常。当 `uncaughtException(thread, ex)` 触发时,依次校验存储目录并创建日志文件夹、采集当前时间戳、应用版本与设备信息(存入 `HashMap`)以及 `ex.printStackTrace()` 完整堆栈写入崩溃文件(注:现代 Android 10+ 分区存储下应写入应用专属目录 `context.getExternalFilesDir("Crash")` 而非直接写外置存储根目录),提示用户后按需延迟重启或将未处理异常交还默认处理器。通过人为触发除零异常验证日志落盘后,同样以 `git rebase` 合入 `develop`。
运行离线中文 URL 分段转码、五级日志 BuildConfig.DEBUG 过滤与 CrashHandler 落盘核验
"""Offline Android capstone verifier for Ch 155: DrySister Part 5 (AS 3.0 Migration, LogUtils & CrashHandler)."""
import json
from pathlib import Path
import tempfile
from urllib.parse import quote
VERSION = (
"CPython 3.12.14 offline Android system-service/sensor/capstone verifier "
"(Android SDK/emulator absent)"
)
LOG_LEVELS = {"V": 2, "D": 3, "I": 4, "W": 5, "E": 6}
class StructuredLogger:
"""Models Android LogUtils gated by BuildConfig.DEBUG and minimum log level."""
def __init__(self, build_config_debug: bool, min_level: str = "V") -> None:
self.debug_enabled = build_config_debug
self.min_rank = LOG_LEVELS[min_level]
self.records: list[dict] = []
def log(self, level: str, tag: str, message: str) -> bool:
rank = LOG_LEVELS[level]
# In release builds (BuildConfig.DEBUG == False), suppress debug/verbose logs;
# full LogUtils gate suppresses all debug output when debug_enabled is False.
if not self.debug_enabled:
return False
if rank < self.min_rank:
return False
self.records.append({"level": level, "tag": tag, "message": message})
return True
def build_crash_report(
timestamp_str: str,
device_info: dict[str, str],
exc_type: str,
exc_msg: str,
) -> str:
lines = [f"crash_time={timestamp_str}"]
for k in sorted(device_info):
lines.append(f"{k}={device_info[k]}")
lines.append(f"exception={exc_type}: {exc_msg}")
return "\n".join(lines) + "\n"
def main() -> None:
# Case 1: AS 3.0 migration — Chinese URL segment percent-encoding & rebase commit linearity
base_prefix = "http://gank.io/api/data/"
encoded_segment = quote("福利", encoding="utf-8").lower()
encoded_full_url = f"{base_prefix}{encoded_segment}/10/1"
# Verify naive full-URL encoding corrupts scheme "://"
corrupted_full_url = quote(f"{base_prefix}福利/10/1", safe="", encoding="utf-8")
# Simulate git rebase: feature commits replayed linearly onto develop tip
develop_commits = ["c1_init", "c2_json", "c3_cache", "c4_db"]
feature_commits = ["f1_as3_gradle", "f2_log_crash"]
rebased_history = develop_commits + feature_commits
c1_actual = {
"encoded_segment": encoded_segment,
"valid_api_url": encoded_full_url,
"naive_full_encode_breaks_scheme": not corrupted_full_url.startswith("http://"),
"rebased_linear_count": len(rebased_history),
"rebased_head": rebased_history[-1],
}
c1_expected = {
"encoded_segment": "%e7%a6%8f%e5%88%a9",
"valid_api_url": "http://gank.io/api/data/%e7%a6%8f%e5%88%a9/10/1",
"naive_full_encode_breaks_scheme": True,
"rebased_linear_count": 6,
"rebased_head": "f2_log_crash",
}
# Case 2: Log level filter (V/D/I/W/E) + BuildConfig.DEBUG guard + CrashHandler file persistence
events = [
("V", "SisterApi", "raw response stream"),
("D", "SisterLoader", "cache lookup key"),
("I", "MainActivity", "page 2 loaded"),
("W", "DiskCache", "near max capacity"),
("E", "Network", "HTTP 500 error"),
]
debug_logger_all = StructuredLogger(build_config_debug=True, min_level="V")
debug_logger_info = StructuredLogger(build_config_debug=True, min_level="I")
release_logger = StructuredLogger(build_config_debug=False, min_level="V")
for lvl, tag, msg in events:
debug_logger_all.log(lvl, tag, msg)
debug_logger_info.log(lvl, tag, msg)
release_logger.log(lvl, tag, msg)
# CrashHandler: catch ZeroDivisionError (1/0), write report to temp Crash/ directory
with tempfile.TemporaryDirectory() as tmp:
crash_dir = Path(tmp) / "Crash"
crash_dir.mkdir(parents=True, exist_ok=True)
try:
_ = 1 // 0
except ZeroDivisionError as exc:
report = build_crash_report(
timestamp_str="2017-12-22_14-30-00",
device_info={"versionName": "1.0.0", "versionCode": "1", "MODEL": "Meilan_E2", "SDK_INT": "26"},
exc_type=type(exc).__name__,
exc_msg=str(exc),
)
crash_file = crash_dir / "crash-2017-12-22_14-30-00.log"
crash_file.write_text(report, encoding="utf-8")
written_lines = crash_file.read_text(encoding="utf-8").strip().splitlines()
c2_actual = {
"debug_all_levels": [r["level"] for r in debug_logger_all.records],
"debug_min_info_levels": [r["level"] for r in debug_logger_info.records],
"release_emitted_count": len(release_logger.records),
"crash_report_line_count": len(written_lines),
"crash_report_has_exception": any("ZeroDivisionError" in ln for ln in written_lines),
}
c2_expected = {
"debug_all_levels": ["V", "D", "I", "W", "E"],
"debug_min_info_levels": ["I", "W", "E"],
"release_emitted_count": 0,
"crash_report_line_count": 6,
"crash_report_has_exception": True,
}
cases = [
{
"name": "as3_url_encoding_and_git_rebase",
"summary": "验证中文路径分段 UTF-8 百分号转码(避免破坏协议头)及 git rebase 线性提交历史",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "logutils_level_filter_and_crashhandler",
"summary": "验证 V/D/I/W/E 五级日志过滤、BuildConfig.DEBUG 开关门控及 CrashHandler 异常落盘采集",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 验证 '福利' 分段转码为 %e7%a6%8f%e5%88%a9、Debug/Release 日志门控过滤与临时目录崩溃报告完整写入。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:f0a97cf6645c294c10805f31a8f5cafd27b75fc2b28b60b6139783bb8157e6ae
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:91263fdd8ae58f6d8013502ac1088badf89fb2baddf614438ba0c9759f2e77f6
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
对包含中文路径参数的 URL(如 `http://gank.io/api/data/福利/10/1`)进行转码时,为什么只能对中文段调用 `URLEncoder.encode()` 而不能编码整条 URL?
展开参考解答
`URLEncoder.encode()` 会把 `:` 和 `/` 等 URL 结构保留分隔符也转义为 `%3A`、`%2F`,导致协议头 `http://` 与路径结构彻底失效;因此必须只针对中文参数段进行 UTF-8 百分号编码。