feat: 优化代码格式和可读性,增强日志清理策略配置
This commit is contained in:
1 parent
dcded08796
commit
917438af2e
12 files changed
+190
-59
No files matched your search
@@ -600,8 +600,13 @@ class underlying_operations:
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
with open(self._screenshot_log_path, "a", encoding="utf-8") as _lf:
|
||||
_lf.write(json.dumps(end_record, ensure_ascii=False) + "\n")
|
||||
with open(
|
||||
self._screenshot_log_path, "a", encoding="utf-8"
|
||||
) as _lf:
|
||||
_lf.write(
|
||||
json.dumps(end_record, ensure_ascii=False)
|
||||
+ "\n"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
|
||||
+3
-3
@@ -186,8 +186,8 @@
|
||||
},
|
||||
"debug_captures": {
|
||||
"enabled": false,
|
||||
"keep_days": 1,
|
||||
"max_files": 100,
|
||||
"keep_days": 3,
|
||||
"max_files": 2000,
|
||||
"auto_cleanup": true,
|
||||
"async_save": false,
|
||||
"log_on_complete": false
|
||||
@@ -210,4 +210,4 @@
|
||||
"yanghao_only": false,
|
||||
"record_room_title_mapping_enabled": true,
|
||||
"enable_back_on_misses": true
|
||||
}
|
||||
}
|
||||
@@ -219,14 +219,18 @@ def find_and_open_fudai_detail(
|
||||
try:
|
||||
# 兜底:使用通用 click 返回坐标
|
||||
rx = int(
|
||||
getattr(analyser, "resolution_ratio_x", 1080) or 1080
|
||||
getattr(analyser, "resolution_ratio_x", 1080)
|
||||
or 1080
|
||||
)
|
||||
ry = int(
|
||||
getattr(analyser, "resolution_ratio_y", 2400) or 2400
|
||||
getattr(analyser, "resolution_ratio_y", 2400)
|
||||
or 2400
|
||||
)
|
||||
back_x = int(50 * rx / 1080)
|
||||
back_y = int(50 * ry / 2400)
|
||||
analyser.operation.click(analyser.device_id, back_x, back_y)
|
||||
analyser.operation.click(
|
||||
analyser.device_id, back_x, back_y
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
|
||||
@@ -202,7 +202,9 @@ class SwipeHandler:
|
||||
return 0
|
||||
|
||||
# 根据配置选择回退方式:'swipe'=滑动回退(默认),'back'=按返回键回退
|
||||
mode = str(getattr(analyser, "reset_after_swipes_action", "swipe") or "swipe").lower()
|
||||
mode = str(
|
||||
getattr(analyser, "reset_after_swipes_action", "swipe") or "swipe"
|
||||
).lower()
|
||||
if mode not in ("swipe", "back"):
|
||||
mode = "swipe"
|
||||
|
||||
@@ -230,7 +232,8 @@ class SwipeHandler:
|
||||
pass
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"流程", "回退直播间 {}/{} (使用返回键)".format(i + 1, back_times)
|
||||
"流程",
|
||||
"回退直播间 {}/{} (使用返回键)".format(i + 1, back_times),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -261,7 +264,9 @@ class SwipeHandler:
|
||||
import os
|
||||
|
||||
adb_cmd = os.environ.get("ADB_EXECUTABLE", "adb") or "adb"
|
||||
if not adb_cmd.startswith('"') and not adb_cmd.endswith('"'):
|
||||
if not adb_cmd.startswith('"') and not adb_cmd.endswith(
|
||||
'"'
|
||||
):
|
||||
adb_cmd = f'"{adb_cmd}"'
|
||||
cmd = (
|
||||
f"{adb_cmd} -s {analyser.device_id} shell input swipe "
|
||||
|
||||
@@ -312,6 +312,18 @@ def cleanup_old_logs(
|
||||
"freed_space_mb": 0.0,
|
||||
}
|
||||
|
||||
def _safe_get_mtime(path: str) -> float:
|
||||
try:
|
||||
return os.path.getmtime(path)
|
||||
except Exception:
|
||||
return 0.0
|
||||
|
||||
def _safe_get_size(path: str) -> int:
|
||||
try:
|
||||
return os.path.getsize(path)
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
try:
|
||||
if not os.path.exists(logs_dir):
|
||||
return stats
|
||||
@@ -322,32 +334,38 @@ def cleanup_old_logs(
|
||||
os.path.join(logs_dir, f"{base_name}_*.log.gz"),
|
||||
]
|
||||
|
||||
all_files = []
|
||||
all_files: list[str] = []
|
||||
for pattern in patterns:
|
||||
all_files.extend(glob.glob(pattern))
|
||||
for p in glob.glob(pattern):
|
||||
# 并发轮转/删除时避免后续排序抛 FileNotFoundError
|
||||
if os.path.exists(p):
|
||||
all_files.append(p)
|
||||
|
||||
if not all_files:
|
||||
return stats
|
||||
|
||||
# 按修改时间排序(最新的在前)
|
||||
all_files.sort(key=os.path.getmtime, reverse=True)
|
||||
all_files.sort(key=_safe_get_mtime, reverse=True)
|
||||
|
||||
# 计算总大小
|
||||
total_size = sum(os.path.getsize(f) for f in all_files if os.path.exists(f))
|
||||
total_size = sum(_safe_get_size(f) for f in all_files if os.path.exists(f))
|
||||
stats["total_size_mb"] = total_size / 1024 / 1024
|
||||
|
||||
# 如果总大小超过限制,先删除最旧的文件
|
||||
max_total_size_bytes = max_total_size_gb * 1024 * 1024 * 1024
|
||||
if total_size > max_total_size_bytes:
|
||||
# 按时间排序,删除最旧的
|
||||
sorted_files = sorted(all_files, key=os.path.getmtime)
|
||||
sorted_files = sorted(
|
||||
[f for f in all_files if os.path.exists(f)],
|
||||
key=_safe_get_mtime,
|
||||
)
|
||||
|
||||
for log_file in sorted_files:
|
||||
if total_size <= max_total_size_bytes:
|
||||
break
|
||||
|
||||
try:
|
||||
file_size = os.path.getsize(log_file)
|
||||
file_size = _safe_get_size(log_file)
|
||||
os.remove(log_file)
|
||||
total_size -= file_size
|
||||
stats["deleted"] += 1
|
||||
@@ -422,6 +440,52 @@ def cleanup_old_logs(
|
||||
return stats
|
||||
|
||||
|
||||
def _load_logging_cleanup_policy_from_config() -> tuple[int, float, int, bool]:
|
||||
"""从 config/config.json 读取日志清理策略。
|
||||
|
||||
返回:
|
||||
(keep_days, max_total_size_gb, compress_after_days, compress)
|
||||
|
||||
说明:
|
||||
- 只负责读取与容错;不做“阈值联动”的业务决策。
|
||||
- 读取失败时回退到模块默认值。
|
||||
"""
|
||||
keep_days = 30
|
||||
max_total_size_gb = 10.0
|
||||
compress_after_days = 7
|
||||
compress = True
|
||||
|
||||
try:
|
||||
import json
|
||||
|
||||
config_path = path_config.get_config_path()
|
||||
if not os.path.exists(config_path):
|
||||
return keep_days, max_total_size_gb, compress_after_days, compress
|
||||
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
cfg = json.load(f)
|
||||
|
||||
log_cfg = cfg.get("logging", {})
|
||||
if isinstance(log_cfg, dict):
|
||||
keep_days = int(log_cfg.get("keep_days", keep_days))
|
||||
max_total_size_gb = float(log_cfg.get("max_total_size_gb", max_total_size_gb))
|
||||
compress_after_days = int(log_cfg.get("compress_after_days", compress_after_days))
|
||||
compress = bool(log_cfg.get("compress_logs", compress))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 基础兜底,避免异常配置导致“全部删光/不清理”
|
||||
if keep_days < 0:
|
||||
keep_days = 0
|
||||
if compress_after_days < 0:
|
||||
compress_after_days = 0
|
||||
if max_total_size_gb <= 0:
|
||||
# 若用户配置为 0/负数,视为禁用“按总量限制”,回退到默认
|
||||
max_total_size_gb = 10.0
|
||||
|
||||
return keep_days, max_total_size_gb, compress_after_days, compress
|
||||
|
||||
|
||||
def get_logger(name: Optional[str] = None) -> logging.Logger:
|
||||
"""获取指定名称的 logger,如果未配置则自动配置"""
|
||||
if not _logging_configured:
|
||||
@@ -1066,23 +1130,36 @@ class LogRotationMonitor:
|
||||
|
||||
def _schedule_cleanup_async(self) -> None:
|
||||
"""如果没有正在运行的清理任务,则在后台线程中启动一次清理。"""
|
||||
# 快速检查,避免频繁加锁
|
||||
if self._cleanup_running:
|
||||
return
|
||||
# 用锁做“唯一运行”判定,避免竞态导致并发启动多个清理线程
|
||||
with self._cleanup_lock:
|
||||
if self._cleanup_running:
|
||||
return
|
||||
self._cleanup_running = True
|
||||
|
||||
keep_days, cfg_max_total_size_gb, compress_after_days, compress = (
|
||||
_load_logging_cleanup_policy_from_config()
|
||||
)
|
||||
|
||||
# 监控告警阈值与清理联动:当触发 WARNING 时,把总量上限压到 warning 阈值附近
|
||||
# 这样“>=500MB 报警”能实际驱动清理生效(而不是仍按 10GB 上限导致无动作)。
|
||||
try:
|
||||
warning_target_gb = max(0.05, float(self.warning_size_mb) / 1024.0)
|
||||
except Exception:
|
||||
warning_target_gb = 0.5
|
||||
|
||||
effective_max_total_size_gb = min(cfg_max_total_size_gb, warning_target_gb)
|
||||
|
||||
def _worker():
|
||||
try:
|
||||
with self._cleanup_lock:
|
||||
self._cleanup_running = True
|
||||
# 使用模块内的 cleanup_old_logs 执行清理,采用默认策略(保留30天、10GB上限)
|
||||
try:
|
||||
cleanup_old_logs(
|
||||
logs_dir=self.logs_dir,
|
||||
base_name=self.base_name,
|
||||
keep_days=30,
|
||||
max_total_size_gb=10.0,
|
||||
compress_after_days=7,
|
||||
compress=True,
|
||||
keep_days=keep_days,
|
||||
max_total_size_gb=effective_max_total_size_gb,
|
||||
compress_after_days=compress_after_days,
|
||||
compress=compress,
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
|
||||
+3
-1
@@ -499,7 +499,9 @@ def main(argv: list[str]) -> int:
|
||||
analyser.reset_after_swipes_enabled = False
|
||||
if getattr(args, "reset_after_swipes_action", None) is not None:
|
||||
try:
|
||||
analyser.reset_after_swipes_action = str(args.reset_after_swipes_action or "swipe")
|
||||
analyser.reset_after_swipes_action = str(
|
||||
args.reset_after_swipes_action or "swipe"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 下滑后返回并重新进入直播间的命令行覆盖(优先级高于 config.json)
|
||||
|
||||
@@ -4,16 +4,24 @@ from douyin.utils import douyin_config
|
||||
|
||||
def main():
|
||||
a = fudai_analyse()
|
||||
print('Before load:')
|
||||
print(' enable_back_on_misses attr ->', getattr(a, 'enable_back_on_misses', None))
|
||||
print(' reset_after_swipes_action attr ->', getattr(a, 'reset_after_swipes_action', None))
|
||||
print(' fudai_exit_after_misses attr ->', getattr(a, 'fudai_exit_after_misses', None))
|
||||
print("Before load:")
|
||||
print(" enable_back_on_misses attr ->", getattr(a, "enable_back_on_misses", None))
|
||||
print(
|
||||
" reset_after_swipes_action attr ->",
|
||||
getattr(a, "reset_after_swipes_action", None),
|
||||
)
|
||||
print(
|
||||
" fudai_exit_after_misses attr ->", getattr(a, "fudai_exit_after_misses", None)
|
||||
)
|
||||
# load from config
|
||||
douyin_config.ConfigManager.load_config_from_file(a)
|
||||
print('\nAfter load_config_from_file:')
|
||||
print(' enable_back_on_misses ->', getattr(a, 'enable_back_on_misses', None))
|
||||
print(' reset_after_swipes_action ->', getattr(a, 'reset_after_swipes_action', None))
|
||||
print(' fudai_exit_after_misses ->', getattr(a, 'fudai_exit_after_misses', None))
|
||||
print("\nAfter load_config_from_file:")
|
||||
print(" enable_back_on_misses ->", getattr(a, "enable_back_on_misses", None))
|
||||
print(
|
||||
" reset_after_swipes_action ->", getattr(a, "reset_after_swipes_action", None)
|
||||
)
|
||||
print(" fudai_exit_after_misses ->", getattr(a, "fudai_exit_after_misses", None))
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -9,11 +9,11 @@ for i in range(8):
|
||||
print("result:", ok)
|
||||
time.sleep(0.6)
|
||||
|
||||
print('\n--- Log snippet ---')
|
||||
print("\n--- Log snippet ---")
|
||||
try:
|
||||
with open('logs/screenshot_calls.log', 'r', encoding='utf-8') as f:
|
||||
with open("logs/screenshot_calls.log", "r", encoding="utf-8") as f:
|
||||
lines = f.read().splitlines()
|
||||
for ln in lines[-120:]:
|
||||
print(ln)
|
||||
except Exception as e:
|
||||
print('Could not read log:', e)
|
||||
print("Could not read log:", e)
|
||||
@@ -1,10 +1,14 @@
|
||||
from douyin.core.douyin_fudai import fudai_analyse
|
||||
from douyin.handlers import douyin_swipe_ops
|
||||
|
||||
|
||||
class DummyOp:
|
||||
def swipe(self, device_id, sx, sy, ex, ey, duration_ms):
|
||||
# minimal output
|
||||
print(f"swipe: device={device_id} from=({sx},{sy}) to=({ex},{ey}) dur={duration_ms}")
|
||||
print(
|
||||
f"swipe: device={device_id} from=({sx},{sy}) to=({ex},{ey}) dur={duration_ms}"
|
||||
)
|
||||
|
||||
def click_back(self, device_id=None):
|
||||
print(f"click_back called, device={device_id}")
|
||||
|
||||
@@ -14,8 +18,8 @@ def main():
|
||||
a.operation = DummyOp()
|
||||
a.device_id = "DUMMY"
|
||||
# use config default of 10 to simulate ten swipes
|
||||
a.fudai_exit_after_misses = int(getattr(a, 'fudai_exit_after_misses', 10) or 10)
|
||||
print('fudai_exit_after_misses =', a.fudai_exit_after_misses)
|
||||
a.fudai_exit_after_misses = int(getattr(a, "fudai_exit_after_misses", 10) or 10)
|
||||
print("fudai_exit_after_misses =", a.fudai_exit_after_misses)
|
||||
# ensure counter starts at 0
|
||||
a._consecutive_no_fudai_count = 0
|
||||
|
||||
@@ -23,19 +27,22 @@ def main():
|
||||
print(f"\n-- swipe #{i} --")
|
||||
douyin_swipe_ops.swipe_up_switch_live(a)
|
||||
# simulate not finding fudai -> increment counter
|
||||
a._consecutive_no_fudai_count = int(getattr(a, '_consecutive_no_fudai_count', 0)) + 1
|
||||
print('consecutive_no_fudai_count =', a._consecutive_no_fudai_count)
|
||||
a._consecutive_no_fudai_count = (
|
||||
int(getattr(a, "_consecutive_no_fudai_count", 0)) + 1
|
||||
)
|
||||
print("consecutive_no_fudai_count =", a._consecutive_no_fudai_count)
|
||||
if a._consecutive_no_fudai_count >= a.fudai_exit_after_misses:
|
||||
print('threshold reached, invoking back')
|
||||
print("threshold reached, invoking back")
|
||||
try:
|
||||
a.operation.click_back(a.device_id)
|
||||
except Exception:
|
||||
print('click_back failed')
|
||||
print("click_back failed")
|
||||
# reset counter as real logic would
|
||||
a._consecutive_no_fudai_count = 0
|
||||
break
|
||||
else:
|
||||
print('\nNo back triggered after 10 swipes')
|
||||
print("\nNo back triggered after 10 swipes")
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,16 +1,19 @@
|
||||
from douyin.core.douyin_fudai import fudai_analyse
|
||||
from douyin.utils import douyin_config
|
||||
|
||||
|
||||
class DummyOp:
|
||||
def __init__(self):
|
||||
self.clicked_back = False
|
||||
self.clicked_coord = None
|
||||
|
||||
def click_back(self, device_id=None):
|
||||
print("DummyOp.click_back called, device_id=", device_id)
|
||||
self.clicked_back = True
|
||||
|
||||
def click(self, device_id, x, y):
|
||||
print(f"DummyOp.click called at ({x},{y}), device_id={device_id}")
|
||||
self.clicked_coord = (x,y)
|
||||
self.clicked_coord = (x, y)
|
||||
|
||||
|
||||
def simulate():
|
||||
@@ -65,5 +68,6 @@ def simulate():
|
||||
else:
|
||||
print("threshold not reached: cur=", cur, "threshold=", threshold)
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
simulate()
|
||||
@@ -1,25 +1,39 @@
|
||||
from douyin.handlers.douyin_swipe_handler import SwipeHandler
|
||||
|
||||
|
||||
class DummyOp:
|
||||
def click_back(self, device_id=None):
|
||||
print('DummyOp.click_back called, device_id=', device_id)
|
||||
print("DummyOp.click_back called, device_id=", device_id)
|
||||
|
||||
def delay(self, s):
|
||||
pass
|
||||
|
||||
|
||||
class DummyAnalyser:
|
||||
def __init__(self):
|
||||
self.operation = DummyOp()
|
||||
self.device_id = 'DUMMY'
|
||||
self.device_id = "DUMMY"
|
||||
self._swipe_times = 5
|
||||
self.reset_after_swipes_enabled = True
|
||||
self.reset_after_swipes = 5
|
||||
self.reset_after_swipes_action = 'back'
|
||||
self.reset_after_swipes_action = "back"
|
||||
self.resolution_ratio_x = 1080
|
||||
self.resolution_ratio_y = 2400
|
||||
self.room_pos = 3
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
a = DummyAnalyser()
|
||||
print('Before maybe_reset, _swipe_times=', a._swipe_times, 'action=', a.reset_after_swipes_action)
|
||||
print(
|
||||
"Before maybe_reset, _swipe_times=",
|
||||
a._swipe_times,
|
||||
"action=",
|
||||
a.reset_after_swipes_action,
|
||||
)
|
||||
SwipeHandler.maybe_reset_after_swipes(a)
|
||||
print('After maybe_reset, _swipe_times=', getattr(a, '_swipe_times', None), 'room_pos=', getattr(a, 'room_pos', None))
|
||||
print(
|
||||
"After maybe_reset, _swipe_times=",
|
||||
getattr(a, "_swipe_times", None),
|
||||
"room_pos=",
|
||||
getattr(a, "room_pos", None),
|
||||
)
|
||||
@@ -1,15 +1,19 @@
|
||||
from douyin.handlers import douyin_swipe_ops
|
||||
from douyin.core.douyin_fudai import fudai_analyse
|
||||
|
||||
|
||||
class DummyOp:
|
||||
def _adb(self):
|
||||
# Return path to non-existing adb to force fallback
|
||||
return "adb"
|
||||
|
||||
def swipe(self, device_id, sx, sy, ex, ey, duration_ms):
|
||||
print(f"DummyOp.swipe called device={device_id} from ({sx},{sy}) to ({ex},{ey}) duration={duration_ms}")
|
||||
print(
|
||||
f"DummyOp.swipe called device={device_id} from ({sx},{sy}) to ({ex},{ey}) duration={duration_ms}"
|
||||
)
|
||||
|
||||
|
||||
def simulate_once(i:int):
|
||||
def simulate_once(i: int):
|
||||
a = fudai_analyse()
|
||||
a.operation = DummyOp()
|
||||
a.device_id = f"DUMMY{i}"
|
||||
@@ -18,6 +22,7 @@ def simulate_once(i:int):
|
||||
print(f"--- simulate swipe #{i} ---")
|
||||
douyin_swipe_ops.swipe_up_switch_live(a)
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
for i in range(1, 11):
|
||||
simulate_once(i)
|
||||
Reference in new issue
Block a user