利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.
Python ai-video-generatorcontent-creationffmpeginstagram-reelsllmpythonshort-videosubtitlestext-to-speechtiktokvideo-automationvideo-workflowworkflow-automationyoutube-shorts
feat(logging): add runtime controls and tracing
harry07036940611cc279
diff --git a/app/config/__init__.py b/app/config/__init__.pyindex 2df95973..348fc817 100644--- a/app/config/__init__.py+++ b/app/config/__init__.py@@ -1,12 +1,23 @@import sysfrom app.config import config-from app.utils.logging_utils import configure_terminal_logger+from app.utils.logging_utils import (+ LOG_LEVELS,+ configure_terminal_logger,+ set_logging_options,+)def __init_logger():# _log_file = utils.storage_dir("logs/server.log")- _lvl = config.log_level+ _lvl = str(config.diagnostics.get("log_level", config.log_level)).strip().upper()+ if _lvl not in LOG_LEVELS:+ _lvl = str(config.log_level).strip().upper()+ if _lvl not in LOG_LEVELS:+ _lvl = "DEBUG"+ # 分别校验两个选项:非法追踪值不能降低用户已有的日志等级。+ _trace = config.diagnostics.get("log_requests", False)+ set_logging_options(_lvl, _trace if isinstance(_trace, bool) else False)configure_terminal_logger(sys.stdout,diff --git a/app/config/config.py b/app/config/config.pyindex fa7ca10e..b84a8772 100644--- a/app/config/config.py+++ b/app/config/config.py@@ -17,6 +17,7 @@ config_file = f"{root_dir}/config.toml"_CONTAINER_CGROUP_MARKERS = ("docker", "containerd", "kubepods", "libpod", "podman")_DOCKER_HOST_GATEWAY_NAME = "host.docker.internal"_config_save_lock = threading.RLock()+_diagnostics_update_lock = threading.Lock()_pending_config_lock = threading.RLock()_pending_config_updates = {}_pending_config_save_requested = False@@ -99,15 +100,21 @@ def update_config_nonblocking(config_section, key, value):返回 True 表示值已经生效,False 表示已进入待更新队列。"""+ return update_config_values_nonblocking(config_section, {key: value})+++def update_config_values_nonblocking(config_section, changes):+ """将同一次操作的关联字段一起排队,避免并发应用时拆散配置。"""# 所有更新都先进入同一队列,再尝试获取配置锁。这样多个页面同时修改同一# 配置项时,写入队列的先后顺序就是最终顺序,不会出现较早线程在获取锁后# 把较新线程已经排队的值误删掉。with _pending_config_lock:- _pending_config_updates[_pending_update_key(config_section, key)] = (- config_section,- key,- copy.deepcopy(value),- )+ for key, value in changes.items():+ _pending_config_updates[_pending_update_key(config_section, key)] = (+ config_section,+ key,+ copy.deepcopy(value),+ )acquired = _config_save_lock.acquire(blocking=False)if not acquired:@@ -119,11 +126,26 @@ def update_config_nonblocking(config_section, key, value):try:_apply_pending_config_updates_locked()- return config_section.get(key, _MISSING) == value+ return all(+ config_section.get(key, _MISSING) == value+ for key, value in changes.items()+ )finally:_config_save_lock.release()+def update_logging_options(level, log_requests):+ """串行发布运行期快照与持久化意图,不等待生成任务的长配置锁。"""+ from app.utils.logging_utils import get_logging_options, set_logging_options++ with _diagnostics_update_lock:+ set_logging_options(level, log_requests)+ level, log_requests = get_logging_options()+ return update_config_values_nonblocking(+ diagnostics, {"log_level": level, "log_requests": log_requests}+ )++def delete_config_nonblocking(config_section, key):"""非阻塞删除 WebUI 配置项。@@ -569,6 +591,7 @@ def save_config():config_to_save["fish_audio"] = dict(fish_audio)config_to_save["voxcpm"] = dict(voxcpm)config_to_save["ui"] = dict(ui)+ config_to_save["diagnostics"] = dict(diagnostics)serialized_config = toml.dumps(config_to_save)# WebUI 完整 rerun 结束时会调用保存。内容没有变化时直接返回,避免每次@@ -615,6 +638,7 @@ def save_config():_cfg = load_config()+diagnostics = _SynchronizedConfig(_cfg.get("diagnostics", {}))app = _SynchronizedConfig(_cfg.get("app", {}))whisper = _cfg.get("whisper", {})proxy = _cfg.get("proxy", {})diff --git a/app/services/elevenlabs_music.py b/app/services/elevenlabs_music.pyindex 5981340b..fad4bb2e 100644--- a/app/services/elevenlabs_music.py+++ b/app/services/elevenlabs_music.py@@ -8,6 +8,8 @@ from typing import Anyimport requestsfrom loguru import logger+from app.utils.request_logging import trace_http_call+from app.config import configfrom app.services import bgm as bgm_servicefrom app.utils import utils@@ -120,7 +122,8 @@ def test_connection() -> dict[str, Any]:if not api_key:raise ElevenLabsAuthenticationError("ElevenLabs API key is required")try:- with requests.get(+ with trace_http_call(+ "GET", requests.get,f"{_base_url()}{SUBSCRIPTION_PATH}",headers={"xi-api-key": api_key},timeout=(15, 30),@@ -326,7 +329,8 @@ def _request_bgm(video_path: str, output_path: str, prompt: str) -> str:request_data["description"] = prompttry:with open(video_path, "rb") as video_file:- response = requests.post(+ response = trace_http_call(+ "POST", requests.post,f"{_base_url()}{VIDEO_TO_MUSIC_PATH}",headers={"xi-api-key": get_api_key()},params={"output_format": "mp3_44100_128"},diff --git a/app/services/kimi_code_oauth.py b/app/services/kimi_code_oauth.pyindex 1b92b5fc..f82b3dd1 100644--- a/app/services/kimi_code_oauth.py+++ b/app/services/kimi_code_oauth.py@@ -29,6 +29,8 @@ import uuidimport requestsfrom loguru import logger+from app.utils.request_logging import trace_http_call+from app import __version__from app.config import config@@ -158,7 +160,8 @@ def request_device_code(region: str) -> dict:if region not in _REGIONS:raise ValueError(f"kimi_code: unknown region '{region}'")url = f"{_REGIONS[region]['auth_base']}/api/oauth/device_authorization"- response = requests.post(+ response = trace_http_call(+ "POST", requests.post,url,headers=_identity_headers(),data={"client_id": client_id()},@@ -197,7 +200,8 @@ def poll_token(region: str, device_code: str) -> dict:- the token payload — approved"""url = f"{_REGIONS[region]['auth_base']}/api/oauth/token"- response = requests.post(+ response = trace_http_call(+ "POST", requests.post,url,headers=_identity_headers(),data={@@ -229,7 +233,8 @@ def poll_token(region: str, device_code: str) -> dict:def _refresh(region: str, refresh_token: str) -> dict:url = f"{_REGIONS[region]['auth_base']}/api/oauth/token"- response = requests.post(+ response = trace_http_call(+ "POST", requests.post,url,headers=_identity_headers(),data={diff --git a/app/services/llm.py b/app/services/llm.pyindex 25b2cf2c..f15e4e26 100644--- a/app/services/llm.py+++ b/app/services/llm.py@@ -16,6 +16,7 @@ from openai.types.chat import ChatCompletionfrom app.config import configfrom app.models.llm_provider import DEFAULT_LLM_PROVIDER_ID, get_llm_providerfrom app.utils import utils+from app.utils.request_logging import trace_sdk_call_max_retries = 5MIN_SCRIPT_PARAGRAPH_NUMBER = 1@@ -392,7 +393,8 @@ def _generate_response(import dashscopefrom dashscope.api_entities.dashscope_response import GenerationResponse- response = dashscope.Generation.call(+ response = trace_sdk_call(+ llm_provider, base_url, dashscope.Generation.call,model=model_name,messages=[{"role": "user", "content": prompt}],api_key=api_key,@@ -450,7 +452,8 @@ def _generate_response(api_key=api_key,http_options=http_options,) as client:- response = client.models.generate_content(+ response = trace_sdk_call(+ llm_provider, base_url, client.models.generate_content,model=model_name,contents=prompt,config=generation_config,@@ -476,7 +479,8 @@ def _generate_response(default_headers={"cf-aig-gateway-id": gateway_id},**_sdk_transport_options(request_timeout, max_retries),)- response = client.chat.completions.create(+ response = trace_sdk_call(+ llm_provider, base_url, client.chat.completions.create,model=model_name,messages=[{"role": "user", "content": prompt}],)@@ -490,7 +494,8 @@ def _generate_response(f"{llm_provider}: model_name is not set, please set it in the config.toml file.")- response = litellm.completion(+ response = trace_sdk_call(+ llm_provider, base_url, litellm.completion,model=model_name,messages=[{"role": "user", "content": prompt}],drop_params=True,@@ -515,7 +520,8 @@ def _generate_response(azure_endpoint=base_url,**_sdk_transport_options(request_timeout, max_retries),)- response = client.chat.completions.create(+ response = trace_sdk_call(+ llm_provider, base_url, client.chat.completions.create,model=model_name, messages=[{"role": "user", "content": prompt}])if response:@@ -701,7 +707,8 @@ def _generate_response(default_headers=kimi_code_oauth.api_headers(),**_sdk_transport_options(None, max_retries),)- response = client.chat.completions.create(+ response = trace_sdk_call(+ llm_provider, base_url, client.chat.completions.create,model=request_model, messages=[{"role": "user", "content": prompt}])if response and isinstance(response, ChatCompletion):@@ -717,7 +724,8 @@ def _generate_response(base_url=base_url,**_sdk_transport_options(request_timeout, max_retries),)- response = sdk_stream = client.chat.completions.create(+ response = sdk_stream = trace_sdk_call(+ llm_provider, base_url, client.chat.completions.create,model=model_name,messages=[{"role": "user", "content": prompt}],extra_body={"enable_thinking": False},@@ -744,7 +752,8 @@ def _generate_response(**_sdk_transport_options(request_timeout, max_retries),)- response = client.chat.completions.create(+ response = trace_sdk_call(+ llm_provider, base_url, client.chat.completions.create,model=model_name, messages=[{"role": "user", "content": prompt}])if response:diff --git a/app/services/loomloom.py b/app/services/loomloom.pyindex 18565070..7cf06d95 100644--- a/app/services/loomloom.py+++ b/app/services/loomloom.py@@ -20,6 +20,8 @@ from urllib.parse import quote, urlsplitimport requestsfrom loguru import logger+from app.utils.request_logging import trace_http_call+DEFAULT_RESULT_PORT_NAME = "output"DEFAULT_BASE_URL = "https://loomloom.shengsuanyun.com/loom/v1"@@ -661,7 +663,8 @@ class LoomLoomScriptBackend:"a LoomLoom credential is required for this request")try:- response = self._session.request(+ response = trace_http_call(+ "REQUEST", self._session.request,method,url,headers={diff --git a/app/services/material.py b/app/services/material.pyindex d18a7c36..47bc480b 100644--- a/app/services/material.py+++ b/app/services/material.py@@ -15,6 +15,8 @@ from urllib.parse import quote_plus, urlencode, urlsplit, urlunsplitimport requestsfrom loguru import logger++from app.utils.request_logging import trace_http_callfrom moviepy.video.io.VideoFileClip import VideoFileClipfrom PIL import Image, UnidentifiedImageError@@ -356,7 +358,8 @@ def search_videos_pexels(logger.info(f"searching videos on pexels: term={search_term!r}")try:- r = requests.get(+ r = trace_http_call(+ "GET", requests.get,query_url,headers=headers,proxies=config.proxy,@@ -466,7 +469,8 @@ def search_videos_pixabay()try:- r = requests.get(+ r = trace_http_call(+ "GET", requests.get,query_url, proxies=config.proxy, verify=_get_tls_verify(), timeout=(30, 60))status_code = int(getattr(r, "status_code", 200))@@ -625,7 +629,8 @@ def search_videos_coverr(logger.info(f"searching videos on coverr: term={search_term!r}")try:- r = requests.get(+ r = trace_http_call(+ "GET", requests.get,query_url,headers=headers,proxies=config.proxy,@@ -845,7 +850,8 @@ def generate_videos_wavespeed(# 提交 POST 绝不自动重试:请求可能已经在远端创建了付费任务,重发会造成# 重复生成和重复扣费(与官方 SDK 的 submission 策略一致)。try:- submit_response = requests.post(+ submit_response = trace_http_call(+ "POST", requests.post,f"{WAVESPEED_API_BASE_URL}/{model_id}",json=payload,headers=headers,@@ -969,7 +975,8 @@ def _wait_for_wavespeed_prediction(consecutive_failures = 0while True:try:- response = requests.get(+ response = trace_http_call(+ "GET", requests.get,f"{WAVESPEED_API_BASE_URL}/predictions/{prediction_id}/result",headers=headers,proxies=config.proxy,@@ -1175,7 +1182,8 @@ def save_video(video_url: str, save_dir: str = "") -> str:delete=False,) as temp_file:temp_path = temp_file.name- with requests.get(+ with trace_http_call(+ "GET", requests.get,video_url,headers=headers,proxies=config.proxy,@@ -1408,7 +1416,8 @@ def _openai_image_download_bytes(for attempt in range(1, OPENAI_IMAGE_MAX_DOWNLOAD_ATTEMPTS + 1):response = Nonetry:- response = requests.get(+ response = trace_http_call(+ "GET", requests.get,image_url,headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "@@ -1538,7 +1547,8 @@ def _request_openai_image(endpoint: str, payload: dict) -> tuple[bytes | None, sheaders["Authorization"] = f"Bearer {api_key}"retryable = Falsetry:- response = requests.post(+ response = trace_http_call(+ "POST", requests.post,endpoint,json=payload,headers=headers,diff --git a/app/services/metaso_minimax.py b/app/services/metaso_minimax.pyindex 68916bc9..a084bbd3 100644--- a/app/services/metaso_minimax.py+++ b/app/services/metaso_minimax.py@@ -17,6 +17,8 @@ from urllib.parse import quote, quote_plus, urlsplitimport requestsfrom loguru import logger+from app.utils.request_logging import trace_http_call+from app.config import configfrom app.models.schema import MaterialInfo, VideoAspect@@ -254,7 +256,8 @@ def generate_videos(# POST 超时或 5xx 发生时,远端可能已经创建并计费。接口没有提供客户端# 幂等键,因此这里绝不自动重发;上层会停止后续关键词,避免重复扣费。try:- response = requests.post(+ response = trace_http_call(+ "POST", requests.post,create_url,json=payload,headers=headers,@@ -378,7 +381,8 @@ def _wait_for_task(# 不会有意越过任务总截止时间。到期后不会再发起下一次轮询。phase_timeout = max(min(remaining / 2.0, 30.0), 0.001)try:- response = requests.get(+ response = trace_http_call(+ "GET", requests.get,query_url,headers=headers,proxies=config.proxy,diff --git a/app/services/muapi.py b/app/services/muapi.pyindex 7ea66bc1..02feff0d 100644--- a/app/services/muapi.py+++ b/app/services/muapi.py@@ -18,6 +18,8 @@ from urllib.parse import quote_plus, urlsplitimport requestsfrom loguru import logger+from app.utils.request_logging import trace_http_call+from app.config import configfrom app.models.schema import MaterialInfo, VideoAspect@@ -237,7 +239,8 @@ def generate_videos(# A timeout or 5xx after POST may mean that MuAPI accepted and billed the# job. Retrying the submission could create a second paid generation.try:- response = requests.post(+ response = trace_http_call(+ "POST", requests.post,videos_url,json=payload,headers=headers,@@ -362,7 +365,8 @@ def _wait_for_task(phase_timeout = max(min(remaining / 2.0, 30.0), 0.001)try:- response = requests.get(+ response = trace_http_call(+ "GET", requests.get,result_url,headers=headers,proxies=config.proxy,diff --git a/app/services/ofox.py b/app/services/ofox.pyindex 4c9858c8..63aafabe 100644--- a/app/services/ofox.py+++ b/app/services/ofox.py@@ -7,6 +7,8 @@ from urllib.parse import quote_plusimport requestsfrom loguru import logger+from app.utils.request_logging import trace_http_call+from app.config import configfrom app.models.schema import MaterialInfo, VideoAspect@@ -261,7 +263,8 @@ def generate_videos(# 提交接口不做自动重试:超时或 5xx 可能发生在付费任务已经创建之后,# 盲目重试会造成重复扣费。只有拿到明确拒绝响应时才判定为确定性失败。try:- response = requests.post(+ response = trace_http_call(+ "POST", requests.post,videos_url,json=payload,headers=headers,@@ -392,7 +395,8 @@ def _wait_for_task(# 网络库仍可能有极小调度误差,下一处 deadline 检查会阻止再次重试。phase_timeout = max(min(remaining / 2.0, 30.0), 0.001)try:- response = requests.get(+ response = trace_http_call(+ "GET", requests.get,f"{videos_url}/{task_id}",headers=headers,proxies=config.proxy,diff --git a/app/services/sonilo.py b/app/services/sonilo.pyindex 66b311ca..69ac3cd4 100644--- a/app/services/sonilo.py+++ b/app/services/sonilo.py@@ -11,6 +11,8 @@ from typing import Anyimport requestsfrom loguru import logger+from app.utils.request_logging import trace_http_call+from app.config import configfrom app.services import bgm as bgm_servicefrom app.utils import utils@@ -114,7 +116,8 @@ def test_connection() -> dict[str, Any]:if not api_key:raise SoniloError("Sonilo API key is required")try:- with requests.get(+ with trace_http_call(+ "GET", requests.get,f"{_base_url()}{SERVICES_PATH}",headers={"Authorization": f"Bearer {api_key}"},timeout=(15, 30),@@ -344,7 +347,8 @@ def _request_bgm(video_path: str, output_path: str, prompt: str) -> str:)try:with open(video_path, "rb") as video_file:- response = requests.post(+ response = trace_http_call(+ "POST", requests.post,f"{_base_url()}{VIDEO_TO_MUSIC_PATH}",headers={"Authorization": f"Bearer {get_api_key()}"},files={"video": (Path(video_path).name, video_file, "video/mp4")},diff --git a/app/services/upload_post.py b/app/services/upload_post.pyindex 2fad4578..7e9cfc59 100644--- a/app/services/upload_post.py+++ b/app/services/upload_post.py@@ -10,6 +10,8 @@ from uuid import uuid4import requestsfrom loguru import logger++from app.utils.request_logging import trace_http_callfrom app.config import config@@ -252,7 +254,8 @@ class UploadPostService:headers = {'Authorization': f'Apikey {self.api_key}'}- response = requests.post(+ response = trace_http_call(+ "POST", requests.post,f"{self.API_BASE}/api/upload",headers=headers,data=data,@@ -356,7 +359,8 @@ class UploadPostService:'Authorization': f'Apikey {self.api_key}'}- response = requests.get(+ response = trace_http_call(+ "GET", requests.get,f"{self.API_BASE}/api/uploadposts/status",params={'request_id': request_id},headers=headers,diff --git a/app/services/version_checker.py b/app/services/version_checker.pyindex 4ee4184e..6f21240a 100644--- a/app/services/version_checker.py+++ b/app/services/version_checker.py@@ -8,6 +8,8 @@ from typing import Finalimport requestsfrom loguru import logger++from app.utils.request_logging import trace_http_callfrom packaging.version import InvalidVersion, Version@@ -54,7 +56,8 @@ def get_available_update(current_version: str) -> str | None:return Nonetry:- response = requests.get(+ response = trace_http_call(+ "GET", requests.get,LATEST_RELEASE_API_URL,headers=RELEASE_CHECK_HEADERS,timeout=RELEASE_CHECK_TIMEOUT,diff --git a/app/services/voice.py b/app/services/voice.pyindex efce0750..36010e30 100644--- a/app/services/voice.py+++ b/app/services/voice.py@@ -24,6 +24,8 @@ import requestsfrom edge_tts import SubMakerfrom edge_tts.srt_composer import Subtitlefrom loguru import logger++from app.utils.request_logging import trace_http_callfrom moviepy.audio.io.AudioFileClip import AudioFileClipfrom openai import OpenAI@@ -216,7 +218,8 @@ def get_elevenlabs_voices(api_key: str) -> list[str]:logger.warning("ElevenLabs voice catalog time budget exhausted; returning partial catalog")breakphase_timeout = min(10.0, remaining / 2.0)- response = requests.get(+ response = trace_http_call(+ "GET", requests.get,url, params=dict(params), headers=headers,timeout=(phase_timeout, phase_timeout), allow_redirects=False,)@@ -320,7 +323,8 @@ def get_kokoro_voices(*, fallback: bool = True) -> list[str]:api_key = config.kokoro.get("api_key", "")if api_key:headers["Authorization"] = f"Bearer {api_key}"- response = requests.get(+ response = trace_http_call(+ "GET", requests.get,f"{base_url}/audio/voices", headers=headers, timeout=5)if response.status_code == 200:@@ -1649,7 +1653,8 @@ def siliconflow_tts(f"start siliconflow tts, model: {model}, voice: {voice}, try: {i + 1}")- response = requests.post(+ response = trace_http_call(+ "POST", requests.post,url,json=payload,headers=headers,@@ -2239,7 +2244,8 @@ def get_minimax_voice_catalog(if tts_endpoint.endswith("/t2a_v2")else f"{tts_endpoint.rstrip('/')}/get_voice")- response = requests.post(+ response = trace_http_call(+ "POST", requests.post,voice_endpoint,json={"voice_type": voice_type},headers={@@ -2401,7 +2407,8 @@ def minimax_tts(text: str, voice_id: str, voice_rate: float, voice_file: str, voreceived_success = Falsetry:logger.info(f"start MiniMax TTS, model: {model}, voice: {voice_id}, try: {attempt + 1}")- response = requests.post(url, json=payload, headers=headers, allow_redirects=False, timeout=120)+ response = trace_http_call(+ "POST", requests.post, url, json=payload, headers=headers, allow_redirects=False, timeout=120)if 300 <= response.status_code < 400:# Redirecting a speech POST may replay a billed synthesis or# forward its input/credentials. Do not follow or resubmit it.@@ -2523,7 +2530,8 @@ def elevenlabs_tts(logger.info(f"start elevenlabs tts, voice_id: {voice_id}, try: {i + 1}")ensure_file_path_exists(voice_file)- response = requests.post(+ response = trace_http_call(+ "POST", requests.post,url,json=payload,headers=headers,@@ -2673,7 +2681,8 @@ def _openai_compatible_tts(logger.info(f"start {provider} tts, voice: {voice}, try: {i + 1}")ensure_file_path_exists(voice_file)- response = requests.post(url, json=payload, headers=headers, allow_redirects=False, timeout=120)+ response = trace_http_call(+ "POST", requests.post, url, json=payload, headers=headers, allow_redirects=False, timeout=120)if 300 <= response.status_code < 400:# Redirecting a speech POST may replay a billed synthesis or# forward its input/credentials. Do not follow or resubmit it.@@ -2926,7 +2935,8 @@ def fish_audio_tts()ensure_file_path_exists(voice_file)- response = requests.post(url, json=payload, headers=headers, allow_redirects=False, timeout=60)+ response = trace_http_call(+ "POST", requests.post, url, json=payload, headers=headers, allow_redirects=False, timeout=60)if 300 <= response.status_code < 400:# Redirecting a speech POST may replay a billed synthesis or# forward its input/credentials. Do not follow or resubmit it.@@ -3271,7 +3281,8 @@ def voxcpm_tts(f"start VoxCPM TTS, model: {model_id}, voice: {voice_id}, "f"try: {attempt + 1}")- response = requests.post(+ response = trace_http_call(+ "POST", requests.post,url,json=payload,headers=headers,diff --git a/app/services/volcengine_seedance.py b/app/services/volcengine_seedance.pyindex 0d476564..ba538c99 100644--- a/app/services/volcengine_seedance.py+++ b/app/services/volcengine_seedance.py@@ -7,6 +7,8 @@ from urllib.parse import quote_plusimport requestsfrom loguru import logger+from app.utils.request_logging import trace_http_call+from app.config import configfrom app.models.schema import MaterialInfo, VideoAspect@@ -263,7 +265,8 @@ def generate_videos(# 提交接口不做自动重试:超时或 5xx 可能发生在付费任务已经创建之后,# 盲目重试会造成重复扣费。只有拿到明确拒绝响应时才判定为确定性失败。try:- response = requests.post(+ response = trace_http_call(+ "POST", requests.post,tasks_url,json=payload,headers=headers,@@ -379,7 +382,8 @@ def _wait_for_task(# 网络库仍可能有极小调度误差,下一处 deadline 检查会阻止再次重试。phase_timeout = max(min(remaining / 2.0, 30.0), 0.001)try:- response = requests.get(+ response = trace_http_call(+ "GET", requests.get,f"{tasks_url}/{task_id}",headers=headers,proxies=config.proxy,diff --git a/app/services/webui_task.py b/app/services/webui_task.pyindex 0a12ca1c..aeebcdaf 100644--- a/app/services/webui_task.py+++ b/app/services/webui_task.py@@ -11,7 +11,11 @@ from app.models.schema import VideoParamsfrom app.services import state as smfrom app.services import task as tmfrom app.services.loomloom import LoomLoomConfirmedVideoRequest-from app.utils.logging_utils import format_log_record, log_scope_thread_id+from app.utils.logging_utils import (+ format_log_record,+ log_scope_thread_id,+ runtime_log_filter,+)# WebUI 的配置保存在进程级全局字典中。原来的同步实现会在完整生成期间持有@@ -76,11 +80,12 @@ def _run_generation(if capture_logs:log_handler_id = logger.add(lambda message: _append_task_log(task_id, str(message)),- level="DEBUG",+ level=0,format=format_log_record,colorize=False,filter=lambda record: (log_scope_thread_id(record["thread"].id) == worker_thread_id+ and runtime_log_filter(record)),)diff --git a/app/utils/logging_utils.py b/app/utils/logging_utils.pyindex 85cb635d..03f37e54 100644--- a/app/utils/logging_utils.py+++ b/app/utils/logging_utils.py@@ -19,6 +19,34 @@ LOG_RECORD_FORMAT = (# 用于收集 WebUI 日志的临时 sink 也会被删除。_terminal_handler_id: int | None = 0_terminal_handler_lock = threading.RLock()+LOG_LEVELS = ("TRACE", "DEBUG", "INFO", "SUCCESS", "WARNING", "ERROR", "CRITICAL")+# 只替换不可变快照,日志线程不获取生成任务持有的配置锁。+_runtime_logging = ("DEBUG", False)+++def get_logging_options() -> tuple[str, bool]:+ return _runtime_logging+++def set_logging_options(level: str, log_requests: bool = False) -> None:+ """即时调整本进程日志,不重建 handler,不中断正在运行的任务。"""+ global _runtime_logging+ level = str(level).strip().upper()+ if level not in LOG_LEVELS:+ raise ValueError(f"unsupported log level: {level}")+ if not isinstance(log_requests, bool):+ raise ValueError("log_requests must be a boolean")+ _runtime_logging = (level, log_requests)+++def runtime_log_filter(record) -> bool:+ level, log_requests = _runtime_logging+ # 请求追踪是独立开关,ERROR 等级下也允许用户显式开启诊断。+ if record["extra"].get("request_trace"):+ return log_requests+ return record["level"].no >= logger.level(level).no++# WebUI 按任务工作线程的 ID 过滤日志。任务为并行下载、片段编码和心跳启动的# 辅助线程有各自的线程 ID,它们写出的日志会被整条丢弃,结果耗时最长的阶段# 在 WebUI 里反而没有任何输出。这里记录“辅助线程 -> 发起它的线程”的映射,@@ -118,6 +146,8 @@ def configure_terminal_logger(sink, level: str, colorize: bool = True) -> int:"""global _terminal_handler_id+ set_logging_options(level, get_logging_options()[1])+with _terminal_handler_lock:if _terminal_handler_id is not None:try:@@ -129,7 +159,8 @@ def configure_terminal_logger(sink, level: str, colorize: bool = True) -> int:_terminal_handler_id = logger.add(sink,- level=level,+ level=0,+ filter=runtime_log_filter,format=format_log_record,colorize=colorize,)diff --git a/app/utils/request_logging.py b/app/utils/request_logging.pynew file mode 100644index 00000000..e4964d0f--- /dev/null+++ b/app/utils/request_logging.py@@ -0,0 +1,211 @@+"""可选的请求参数追踪;不读取响应正文,不改变重试或网络传输行为。"""++import json+import re+from collections.abc import Mapping+from itertools import islice+from time import perf_counter+from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit+from uuid import uuid4++from loguru import logger+from pydantic import BaseModel++from app.utils.logging_utils import get_logging_options+++_REDACTED = "[REDACTED]"+_MAX_STRING = 1000+_MAX_PAYLOAD = 12000+_SECRET_KEY = re.compile(+ r"authorization|cookie|password|passwd|secret|credential|signature|"+ r"apikey|accesskey|privatekey|clientkey|devicecode|usercode|authorizationcode|"+ r"(?:access|refresh|id|auth|api|bearer)token"+)+_TOKEN = re.compile(+ r"\b(?:sk|rk|sess|ghp|github_pat)[-_][A-Za-z0-9_-]{8,}|"+ r"\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+"+)+_URL = re.compile(r"https?://[^\s<>\"']+", re.IGNORECASE)+_MEDIA_KEYS = frozenset(+ {+ "audio",+ "audiodata",+ "audiobase64",+ "base64",+ "b64json",+ "bytes",+ "file",+ "files",+ "filedata",+ "image",+ "imagedata",+ "imagebase64",+ "video",+ }+)+++def _safe_url(value: str) -> str:+ """查询参数全部遮盖,避免漏掉供应商自定义的签名字段。"""+ try:+ parts = urlsplit(value)+ netloc = parts.netloc.rsplit("@", 1)[-1]+ query = urlencode([(k, _REDACTED) for k, _ in parse_qsl(parts.query)])+ return _TOKEN.sub(+ _REDACTED, urlunsplit((parts.scheme, netloc, parts.path, query, ""))+ )[:_MAX_STRING]+ except ValueError:+ return "[invalid URL]"+++def _safe_string(value: str) -> str:+ if value.lstrip().lower().startswith("data:"):+ return "[media omitted]"+ if len(value) >= 256 and re.fullmatch(r"[A-Za-z0-9+/=\r\n]+", value):+ return "[base64 omitted]"+ value = _TOKEN.sub(_REDACTED, value)+ value = _URL.sub(lambda match: _safe_url(match.group()), value)+ return value[:_MAX_STRING] + ("… [truncated]" if len(value) > _MAX_STRING else "")+++def _safe_query_params(value):+ """与 URL 内的 query 保持一致,遮盖所有值,兼容 requests 的参数格式。"""+ if isinstance(value, Mapping):+ return {_safe_string(str(key)): _REDACTED for key in islice(value, 30)}+ if isinstance(value, (list, tuple)):+ return [+ [_safe_string(str(pair[0])), _REDACTED]+ for pair in value[:30]+ if isinstance(pair, (list, tuple)) and len(pair) == 2+ ]+ return "[query values omitted]"+++def sanitize_payload(value):+ """限制深度、节点数和文本长度;未知对象只记录类型,不调用其 repr。"""+ remaining = 100++ def visit(item, depth=0):+ nonlocal remaining+ remaining -= 1+ if remaining < 0 or depth > 6:+ return "[truncated]"+ if isinstance(item, Mapping):+ result = {}+ for index, (key, child) in enumerate(item.items()):+ if index >= 30 or remaining <= 0:+ result["…"] = "[truncated]"+ break+ key = str(key)+ normalized = re.sub(r"[^a-z0-9]", "", key.lower())+ if normalized in {+ "key",+ "token",+ "headers",+ "cookies",+ } or _SECRET_KEY.search(normalized):+ result[_safe_string(key)] = _REDACTED+ elif normalized in {"params", "extraquery", "queryparams"}:+ result[_safe_string(key)] = _safe_query_params(child)+ elif normalized in _MEDIA_KEYS:+ result[_safe_string(key)] = "[media omitted]"+ else:+ result[_safe_string(key)] = visit(child, depth + 1)+ return result+ if isinstance(item, (list, tuple)):+ return [visit(child, depth + 1) for child in item[:10]] + (+ ["[truncated]"] if len(item) > 10 else []+ )+ if isinstance(item, str):+ return _safe_string(item)+ if isinstance(item, BaseModel):+ return visit(item.model_dump(mode="json", exclude_none=True), depth + 1)+ if item is None or isinstance(item, (bool, int, float)):+ return item+ return f"[{type(item).__name__} omitted]"++ return visit(value)+++def _emit(event: dict) -> None:+ # 诊断失败不能阻断付费提交、污染业务异常或触发额外重试。+ try:+ logger.bind(request_trace=True).info(+ "request_trace {}", json.dumps(event, ensure_ascii=False)+ )+ except Exception:+ pass+++def _trace_call(kind, method, endpoint, payload, send, *args, **kwargs):+ if not get_logging_options()[1]:+ return send(*args, **kwargs)+ trace_id = uuid4().hex[:12]+ try:+ parameters = sanitize_payload(payload)+ summary = json.dumps(parameters, ensure_ascii=False)+ _emit(+ {+ "event": "request",+ "id": trace_id,+ "kind": kind,+ "method": method,+ "endpoint": _safe_url(str(endpoint)),+ "parameters": parameters+ if len(summary) <= _MAX_PAYLOAD+ else summary[:_MAX_PAYLOAD],+ "truncated": len(summary) > _MAX_PAYLOAD,+ }+ )+ except Exception:+ pass+ started = perf_counter()+ try:+ response = send(*args, **kwargs)+ except Exception as exc:+ _emit(+ {+ "event": "error",+ "id": trace_id,+ "error_type": type(exc).__name__,+ "elapsed_ms": round((perf_counter() - started) * 1000, 1),+ }+ )+ raise+ # 不访问 .content/.text/.json(),避免提前消耗 SSE、音频和大文件下载。+ try:+ status = getattr(response, "status_code", None)+ except Exception:+ status = None+ _emit(+ {+ "event": "response",+ "id": trace_id,+ "status": status if isinstance(status, int) else None,+ "elapsed_ms": round((perf_counter() - started) * 1000, 1),+ }+ )+ return response+++def trace_http_call(method, send, url, *args, **kwargs):+ """包装项目显式发出的 requests 请求,原参数和返回对象保持不变。"""+ payload = {+ key: kwargs[key] for key in ("params", "json", "data", "files") if key in kwargs+ }+ # 原始表单/二进制正文不能可靠按字段脱敏,只允许查看结构化参数。+ if "data" in payload and not isinstance(payload["data"], Mapping):+ payload["data"] = "[raw body omitted]"+ if method.upper() == "REQUEST":+ # Session.request 的第一个位置参数是 method,第二个才是 URL。+ method, url, args = url, args[0], args[1:]+ return _trace_call(+ "http", method, url, payload, send, method, url, *args, **kwargs+ )+ return _trace_call("http", method, url, payload, send, url, *args, **kwargs)+++def trace_sdk_call(provider, endpoint, send, **kwargs):+ """记录 SDK 调用参数;不声称覆盖 SDK 内部重试或其最终 wire JSON。"""+ return _trace_call("sdk", provider, endpoint, kwargs, send, **kwargs)diff --git a/cli.py b/cli.pyindex 59d62369..b49c07ec 100644--- a/cli.py+++ b/cli.py@@ -1718,12 +1718,12 @@ def _run_batch_tasks(args: argparse.Namespace, tasks: list[VideoParams]) -> int:def run_cli(argv: Sequence[str] | None = None) -> int:args = parse_args(argv)- from app.config import config- from app.utils.logging_utils import configure_terminal_logger+ import app.config # noqa: F401 -- 初始化配置及进程日志设置。+ from app.utils.logging_utils import configure_terminal_logger, get_logging_options# 配置模块默认把终端日志发往 stdout。CLI 的 stdout 是机器可读 JSON,# 必须在素材预处理等步骤开始前切到 stderr,帮助和参数错误仍保持延迟导入。- configure_terminal_logger(sys.stderr, level=config.log_level, colorize=False)+ configure_terminal_logger(sys.stderr, level=get_logging_options()[0], colorize=False)if args.batch_file:try:tasks = _build_batch_tasks(args)diff --git a/config.example.toml b/config.example.tomlindex 86d4c011..0dbc5ca4 100644--- a/config.example.toml+++ b/config.example.toml@@ -11,6 +11,18 @@ log_level = "DEBUG"listen_host = "0.0.0.0"listen_port = 8080+[diagnostics]+# Optional override for the top-level log_level, shared by API, CLI and WebUI.+# log_level = "INFO"+# Request tracing is independent of log level and disabled by default.+# It logs redacted request parameters and response status/timing, never response+# bodies. Prompts may be visible; only enable while troubleshooting.+# WebUI: Settings > Interface > Diagnostic logging; Apply takes effect immediately+# in that process. Other processes / manual file edits require a restart.+# 请求追踪独立于日志等级,默认关闭;提示词可能出现在日志中。+# WebUI 设置中的诊断日志可立即生效;其它进程及手工修改配置后需要重启。+log_requests = false+[app]# Optional protection for API routes and generated files under /tasks.diff --git a/docs/diagnostic-logging.md b/docs/diagnostic-logging.mdnew file mode 100644index 00000000..245cfc7d--- /dev/null+++ b/docs/diagnostic-logging.md@@ -0,0 +1,40 @@+# 诊断日志++在 WebUI 的 **设置 → 界面设置 → 诊断日志** 中选择日志等级,按需开启+**记录 API 请求参数**,点击 **应用日志设置**。设置立即作用于当前服务,+包括正在运行任务的后续日志;同一服务的所有浏览器会话共用该设置。+开启「隐藏日志」只隐藏界面日志,不会关闭终端输出。++API、CLI 和 WebUI 使用相同的配置:++```toml+[diagnostics]+log_level = "INFO"+log_requests = false+```++`log_level` 可选 TRACE、DEBUG、INFO、SUCCESS、WARNING、ERROR、CRITICAL。+省略时沿用原来的顶层 `log_level`,默认 DEBUG。手工修改文件后需要重启,+WebUI 的「应用」只即时更新当前进程,不会远程修改其它 API 或 CLI 进程。++请求追踪是独立开关,在 ERROR 等级下也能开启。它默认关闭,记录内容为:++- 请求 ID、HTTP 方法、脱敏地址、经过长度限制的请求参数。+- 返回状态(可取得时)、耗时,或失败的异常类型。+- LLM SDK 调用参数。此处是 SDK 的输入,不是 SDK 最终发送的原始 JSON;+ SDK 内部自动重试不会逐次显示。流式请求的耗时只统计到取得响应或流对象,+ 不包含后续下载时间。++覆盖项目显式使用 `requests` 的素材、视频、语音、发布及登录等请求,以及+OpenAI 兼容、Azure OpenAI、Qwen、Gemini 和 LiteLLM 文案调用。+不捕获浏览器自身的网络流量、入站 API 正文、CLI 子进程、Edge TTS WebSocket+或其它 SDK 内部传输。正常应用日志与第三方 SDK 自己的日志等级也不是同一开关。++不会记录请求头、响应正文或上传文件内容。密钥、Token、Cookie、密码及签名+字段会遮盖,URL 查询参数的值统一隐藏,音视频/base64 等内容省略。原始+非结构化请求体不记录。**提示词和其它业务参数可能出现在日志中**,排查结束后+请关闭追踪,分享日志前仍需检查其中是否包含私人内容。诊断不会向外部发送日志,+也不会额外发起、重试或重放请求。++CLI 日志仍输出到 stderr,stdout 保持机器可读 JSON。WebUI 任务日志沿用现有+线程归属过滤和条数上限,不会因为切换等级移除正在运行任务的日志处理器。diff --git a/test/services/test_request_logging.py b/test/services/test_request_logging.pynew file mode 100644index 00000000..f12e1f6f--- /dev/null+++ b/test/services/test_request_logging.py@@ -0,0 +1,381 @@+import io+import json+import threading+from types import SimpleNamespace+from unittest.mock import Mock, patch++import pytest+import requests+from loguru import logger++from app.config import config+from app.services import webui_task+from app.models.schema import VideoParams+from app.utils import logging_utils as logs+from app.utils import request_logging as trace++[email protected](autouse=True)+def restore_logging_options():+ previous = logs.get_logging_options()+ yield+ logs.set_logging_options(*previous)+++def output():+ sink = io.StringIO()+ handler = logger.add(+ sink, level=0, filter=logs.runtime_log_filter, format="{message}"+ )+ try:+ yield sink+ finally:+ logger.remove(handler)+++def test_runtime_level_changes_apply_to_existing_handlers(output):+ logs.set_logging_options("ERROR")+ logger.debug("hidden-debug")+ logger.error("visible-error")+ logs.set_logging_options("DEBUG")+ logger.debug("visible-debug")+ assert "hidden-debug" not in output.getvalue()+ assert "visible-error" in output.getvalue()+ assert "visible-debug" in output.getvalue()++[email protected]("level,enabled", [("invalid", False), ("INFO", "false")])+def test_invalid_settings_do_not_replace_current_snapshot(level, enabled):+ logs.set_logging_options("WARNING", True)+ with pytest.raises(ValueError):+ logs.set_logging_options(level, enabled)+ assert logs.get_logging_options() == ("WARNING", True)+++def test_disabled_tracing_never_serializes_or_inspects_response(output):+ logs.set_logging_options("DEBUG", False)+ response = object()+ send = Mock(return_value=response)+ payload = {"api_key": "hidden"}+ with patch.object(trace, "sanitize_payload", side_effect=AssertionError):+ assert (+ trace.trace_http_call("POST", send, "https://example.test", json=payload)+ is response+ )+ send.assert_called_once_with("https://example.test", json=payload)+ assert output.getvalue() == ""+++def test_request_parameters_redacted_without_modifying_original(output):+ logs.set_logging_options("ERROR", True)+ response = SimpleNamespace(status_code=201)+ send = Mock(return_value=response)+ payload = {+ "model": "test-model",+ "messages": [{"content": "visible prompt"}],+ "nested": {"API-Key": "private-api-key", "refresh_token": "private-refresh"},+ "audio": "private-media",+ "files": {"voice": b"private-file"},+ "url": "https://user:[email protected]/file?custom_signature=private-signature",+ }+ headers = {"Authorization": "Bearer private-auth", "Cookie": "private-cookie"}+ result = trace.trace_http_call(+ "POST",+ send,+ "https://user:[email protected]/v1?secret=private-url-key",+ json=payload,+ headers=headers,+ timeout=5,+ allow_redirects=False,+ )+ assert result is response+ assert send.call_args.kwargs["json"] is payload+ assert send.call_args.kwargs["headers"] is headers+ assert payload["nested"]["API-Key"] == "private-api-key"+ records = [+ json.loads(line.removeprefix("request_trace "))+ for line in output.getvalue().splitlines()+ ]+ assert [r["event"] for r in records] == ["request", "response"]+ assert records[0]["id"] == records[1]["id"]+ assert records[1]["status"] == 201+ assert "visible prompt" in output.getvalue()+ assert "test-model" in output.getvalue()+ assert "private-" not in output.getvalue()+++def test_failure_does_not_retry_or_replace_exception(output):+ logs.set_logging_options("DEBUG", True)+ error = requests.Timeout("private-token-in-error")+ send = Mock(side_effect=error)+ with pytest.raises(requests.Timeout) as caught:+ trace.trace_http_call(+ "POST", send, "https://example.test", json={"prompt": "hello"}+ )+ assert caught.value is error+ send.assert_called_once()+ assert '"error_type": "Timeout"' in output.getvalue()+ assert "private-token-in-error" not in output.getvalue()+++def test_diagnostics_failure_never_prevents_request_or_changes_result():+ logs.set_logging_options("DEBUG", True)+ response = object()+ send = Mock(return_value=response)+ with patch.object(trace, "sanitize_payload", side_effect=RuntimeError):+ assert trace.trace_http_call("POST", send, "https://example.test") is response+ send.assert_called_once()+++def test_streaming_response_is_not_consumed(output):+ logs.set_logging_options("INFO", True)++ class Stream:+ status_code = 200++ @property+ def content(self):+ raise AssertionError("stream must not be read")++ text = content++ def json(self):+ raise AssertionError("stream must not be read")++ response = Stream()+ send = Mock(return_value=response)+ assert (+ trace.trace_http_call("GET", send, "https://example.test/audio", stream=True)+ is response+ )+ send.assert_called_once_with("https://example.test/audio", stream=True)+++def test_session_request_keeps_original_method_and_arguments(output):+ logs.set_logging_options("INFO", True)+ send = Mock(return_value=SimpleNamespace(status_code=200))+ trace.trace_http_call(+ "REQUEST", send, "POST", "https://example.test", json={"model": "test"}+ )+ send.assert_called_once_with("POST", "https://example.test", json={"model": "test"})+++def test_sdk_parameters_log_without_consuming_stream(output):+ logs.set_logging_options("DEBUG", True)+ stream = iter([1, 2])+ send = Mock(return_value=stream)+ assert (+ trace.trace_sdk_call(+ "qwen",+ "https://example.test",+ send,+ api_key="private-key",+ messages=[{"content": "hello"}],+ )+ is stream+ )+ assert next(stream) == 1+ assert "private-key" not in output.getvalue()+ assert "hello" in output.getvalue()+++def test_payload_limits_cycles_media_and_embedded_tokens():+ payload = {+ "prompt": "token sk-testtoken123456 and " + "text " * 5000,+ "media": "data:audio/wav;base64,private-media",+ "unknown": object(),+ }+ payload["cycle"] = payload+ text = json.dumps(trace.sanitize_payload(payload))+ assert len(text) < 12000+ assert "sk-testtoken123456" not in text+ assert "private-media" not in text+ assert "[truncated]" in text+++def test_trace_can_be_disabled_on_existing_logger(output):+ send = Mock(return_value=SimpleNamespace(status_code=200))+ logs.set_logging_options("INFO", True)+ trace.trace_http_call("GET", send, "https://example.test")+ before = output.getvalue()+ logs.set_logging_options("INFO", False)+ trace.trace_http_call("GET", send, "https://example.test")+ assert output.getvalue() == before+++def test_active_webui_task_obeys_runtime_level_without_losing_its_sink():+ task_id = "runtime-diagnostic-test"++ def run(**kwargs):+ logger.debug("visible-before-change")+ logger.error("always-visible")++ def update():+ # 模拟用户在另一线程调试持有配置锁的运行任务。+ logs.set_logging_options("ERROR", True)++ thread = threading.Thread(target=update)+ thread.start()+ thread.join(timeout=1)+ assert not thread.is_alive()+ logger.debug("hidden-after-change")+ trace.trace_http_call(+ "POST",+ lambda *a, **kw: SimpleNamespace(status_code=200),+ "https://example.test",+ json={"prompt": "task-trace"},+ )+ return {"ok": True}++ logs.set_logging_options("DEBUG", False)+ with patch.object(webui_task.tm, "start", side_effect=run):+ assert webui_task._run_generation(+ task_id, VideoParams(video_subject="test"), True+ ) == {"ok": True}+ text = "\n".join(webui_task.get_task_logs(task_id))+ assert "visible-before-change" in text+ assert "always-visible" in text+ assert "hidden-after-change" not in text+ assert "task-trace" in text+++def test_diagnostics_settings_persist_without_changing_legacy_level(tmp_path):+ with (+ patch.object(config, "config_file", str(tmp_path / "config.toml")),+ patch.object(config, "root_dir", str(tmp_path)),+ patch.object(config, "_cfg", dict(config._cfg)),+ patch.object(+ config, "diagnostics", {"log_level": "ERROR", "log_requests": True}+ ),+ ):+ config.save_config()+ import toml++ saved = toml.load(tmp_path / "config.toml")+ assert saved["diagnostics"] == {"log_level": "ERROR", "log_requests": True}+++def test_sdk_config_model_is_serialized_and_redacted():+ from pydantic import BaseModel++ class SDKConfig(BaseModel):+ temperature: float = 0.5+ api_key: str = "private-key"++ payload = trace.sanitize_payload({"config": SDKConfig()})+ assert payload["config"]["temperature"] == 0.5+ assert payload["config"]["api_key"] == "[REDACTED]"+++ "params",+ [+ {"api_key": "opaque-query-secret", "custom_auth": "opaque-query-secret"},+ [("api_key", "opaque-query-secret"), ("custom_auth", "opaque-query-secret")],+ "custom_auth=opaque-query-secret",+ ],+)+def test_every_query_parameter_value_is_redacted(params, output):+ logs.set_logging_options("ERROR", True)+ send = Mock(return_value=SimpleNamespace(status_code=200))+ trace.trace_http_call("GET", send, "https://example.test", params=params)+ assert send.call_args.kwargs["params"] is params+ assert "opaque-query-secret" not in output.getvalue()+++def test_invalid_trace_config_preserves_valid_error_level(tmp_path):+ import os+ import subprocess+ import sys++ (tmp_path / "config.toml").write_text(+ 'log_level="ERROR"\n[diagnostics]\nlog_requests="false"\n'+ )+ run = subprocess.run(+ [+ sys.executable,+ "-c",+ "from app.config import config; from app.utils.logging_utils import get_logging_options; import json; print(json.dumps(get_logging_options()))",+ ],+ env=dict(os.environ, MPT_HOME=str(tmp_path)),+ capture_output=True,+ text=True,+ check=True,+ timeout=15,+ )+ assert json.loads(run.stdout) == ["ERROR", False]+++def test_concurrent_logging_updates_keep_runtime_and_saved_options_together(tmp_path):+ """两个会话在任务持锁时同时应用,保存与运行状态必须采用同一组值。"""+ import toml++ acquired = threading.Event()+ release_task = threading.Event()+ a_entered = threading.Event()+ release_a = threading.Event()+ b_entered = threading.Event()+ errors = []+ original_update = config.update_config_values_nonblocking++ def task():+ with config.runtime_config_lock():+ acquired.set()+ release_task.wait(5)++ def delay_a(section, changes):+ if threading.current_thread().name == "logging-A":+ a_entered.set()+ assert release_a.wait(5)+ return original_update(section, changes)++ def apply(level, enabled):+ try:+ if threading.current_thread().name == "logging-B":+ b_entered.set()+ config.update_logging_options(level, enabled)+ except Exception as exc:+ errors.append(exc)++ with (+ patch.object(config, "config_file", str(tmp_path / "config.toml")),+ patch.object(config, "root_dir", str(tmp_path)),+ patch.object(config, "_cfg", dict(config._cfg)),+ patch.object(config, "diagnostics", {}),+ patch.object(config, "update_config_values_nonblocking", side_effect=delay_a),+ ):+ threads = [+ threading.Thread(target=task),+ threading.Thread(target=apply, args=("INFO", True), name="logging-A"),+ threading.Thread(target=apply, args=("ERROR", False), name="logging-B"),+ ]+ try:+ threads[0].start()+ assert acquired.wait(5)+ threads[1].start()+ assert a_entered.wait(5)+ threads[2].start()+ assert b_entered.wait(5)+ release_a.set()+ threads[1].join(5)+ threads[2].join(5)+ assert not threads[1].is_alive() and not threads[2].is_alive()+ assert logs.get_logging_options() == ("ERROR", False)+ finally:+ release_a.set()+ release_task.set()+ for thread in threads:+ if thread.ident is not None:+ thread.join(5)+ assert not errors+ # 后台刷新退出后再恢复被 patch 的配置,避免写入用户配置。+ config.try_save_config()+ import time++ deadline = time.monotonic() + 5+ while config._pending_config_flush_scheduled and time.monotonic() < deadline:+ time.sleep(0.005)+ assert not config._pending_config_flush_scheduled+ saved = toml.load(tmp_path / "config.toml")["diagnostics"]+ assert (saved["log_level"], saved["log_requests"]) == logs.get_logging_options()diff --git a/test/services/test_webui_i18n.py b/test/services/test_webui_i18n.pyindex d241d6a8..6dfa2bdb 100644--- a/test/services/test_webui_i18n.py+++ b/test/services/test_webui_i18n.py@@ -22,6 +22,13 @@ PROVIDER_TIPS_PREFIXES = (# 避免把完全相同的品牌名复制十份,也避免长说明后续只更新部分语言。ENGLISH_FALLBACK_KEYS = frozenset({+ "Diagnostic Logging",+ "Diagnostic Logging Help",+ "Log Level",+ "Trace API Requests",+ "Trace API Requests Help",+ "Apply Logging Settings",+ "Logging Settings Applied","AI Video Quote Required","AI Video Quote Retained For Retry","AI Video Quote Estimate Incomplete",diff --git a/test/services/test_webui_logging_settings.py b/test/services/test_webui_logging_settings.pynew file mode 100644index 00000000..335b6fd1--- /dev/null+++ b/test/services/test_webui_logging_settings.py@@ -0,0 +1,47 @@+from pathlib import Path+from unittest.mock import patch++from streamlit.testing.v1 import AppTest++from app.config import config+from app.utils.logging_utils import get_logging_options, set_logging_options+++def test_logging_form_applies_runtime_and_persisted_settings():+ """真实执行设置弹窗的 Streamlit 控件,修改等级及追踪后无需重启。"""+ previous = get_logging_options()+ diagnostics = {}+ try:+ set_logging_options("DEBUG", False)+ with (+ patch.object(config, "diagnostics", diagnostics),+ patch.object(+ config,+ "app",+ dict(config.app, llm_provider="openai", openai_api_key=""),+ ),+ patch.object(config, "ui", dict(config.ui, language="en")),+ patch.object(config, "try_save_config", return_value=True),+ ):+ app = AppTest.from_file(+ str(Path(__file__).resolve().parents[2] / "webui/Main.py"),+ default_timeout=15,+ )+ app.session_state["settings_dialog_open"] = True+ app.run()+ assert not app.exception+ app.selectbox(key="diagnostic_log_level").select("ERROR")+ app.checkbox(key="diagnostic_log_requests").check()+ button = next(b for b in app.button if b.label == "Apply logging settings")+ button.click().run()+ assert not app.exception+ assert get_logging_options() == ("ERROR", True)+ assert diagnostics == {"log_level": "ERROR", "log_requests": True}+ app.checkbox(key="diagnostic_log_requests").uncheck()+ next(+ b for b in app.button if b.label == "Apply logging settings"+ ).click().run()+ assert not app.exception+ assert get_logging_options() == ("ERROR", False)+ finally:+ set_logging_options(*previous)diff --git a/webui/Main.py b/webui/Main.pyindex a811e935..c7274c48 100644--- a/webui/Main.py+++ b/webui/Main.py@@ -65,8 +65,13 @@ from app.services import sonilo as sonilo_servicefrom app.services import state as smfrom app.services import task as tmfrom app.services import version_checker-from app.utils.logging_utils import configure_terminal_logger+from app.utils.logging_utils import (+ LOG_LEVELS,+ configure_terminal_logger,+ get_logging_options,+)from app.utils import utils+from app.utils.request_logging import trace_http_callst.set_page_config(page_title="MoneyPrinterTurbo",@@ -1914,7 +1919,7 @@ def init_log():# 基础日志 Handler 属于进程级资源,而不是页面会话状态。Streamlit 每次组件# 交互都会 rerun 页面脚本,代码热重载也可能让缓存失效。日志初始化只能# 精确替换终端 Handler,不能清空正在生成任务使用的 WebUI 临时 Handler。- _lvl = "DEBUG"+ _lvl = get_logging_options()[0]return configure_terminal_logger(sys.stdout,@@ -2646,7 +2651,8 @@ def get_groq_model_ids(api_key: str, base_url: str) -> list[str]:models_url = f"{normalized_base_url}/models"try:- response = requests.get(+ response = trace_http_call(+ "GET", requests.get,models_url,headers={"Authorization": f"Bearer {api_key}"},timeout=10,@@ -3177,6 +3183,28 @@ def _render_key_backup_settings(panel):# -----------------------------------------------------------------------------+def _render_logging_settings():+ level, log_requests = get_logging_options()+ with st.expander(tr("Diagnostic Logging")):+ st.caption(tr("Diagnostic Logging Help"))+ with st.form("diagnostic_logging_form"):+ selected_level = st.selectbox(+ tr("Log Level"), LOG_LEVELS, index=LOG_LEVELS.index(level),+ key="diagnostic_log_level",+ )+ selected_trace = st.checkbox(+ tr("Trace API Requests"), value=log_requests,+ key="diagnostic_log_requests",+ help=tr("Trace API Requests Help"),+ )+ apply = st.form_submit_button(tr("Apply Logging Settings"))+ if apply:+ # 诊断不改变生成参数,直接生效;持久化仍走非阻塞配置队列。+ config.update_logging_options(selected_level, selected_trace)+ _save_runtime_config()+ st.success(tr("Logging Settings Applied"))++# 设置属于低频操作,使用中等尺寸 Dialog 避免长期占用主页面纵向空间,# 同时控制阅读行宽,避免弹窗在宽屏设备上显得过于松散。# Dialog 继承 fragment 行为,内部控件交互只重绘弹窗;函数末尾单独保存配置,@@ -3325,6 +3353,7 @@ def _render_settings_dialog():key="hide_log_checkbox",)_set_runtime_config("ui", "hide_log", hide_log)+ _render_logging_settings()_render_cache_management_settings(cache_config_panel)# 密钥恢复会写回配置并清除密码控件状态,必须在下面渲染这些控件之前执行。diff --git a/webui/i18n/en.json b/webui/i18n/en.jsonindex 4edf580f..970231ba 100644--- a/webui/i18n/en.json+++ b/webui/i18n/en.json@@ -603,6 +603,13 @@"kimi_code.oauth.region_mismatch": "Signed in for region \"{authorized}\", but the selected API Platform is \"{selected}\". Requests will use \"{authorized}\" to match your credential; sign in again to switch regions.","kimi_code.oauth.network_error": "Could not reach the Kimi authorization service (network error). Check your connection, then start sign-in again.","kimi_code.oauth.changed": "Sign-in state changed in another page. This authorization has stopped; sign in again if needed.",- "kimi_code.oauth.poll_retry": "Network error while checking the authorization status; retrying automatically…"+ "kimi_code.oauth.poll_retry": "Network error while checking the authorization status; retrying automatically…",+ "Diagnostic Logging": "Diagnostic logging",+ "Diagnostic Logging Help": "Changes apply immediately to this service and all its browser sessions.",+ "Log Level": "Log level",+ "Trace API Requests": "Trace API request parameters",+ "Trace API Requests Help": "Independent of log level and off by default. Records redacted parameters, status and timing. Prompts may be visible. Media and response bodies are omitted. Turn off after troubleshooting.",+ "Apply Logging Settings": "Apply logging settings",+ "Logging Settings Applied": "Logging settings applied to this service."}}diff --git a/webui/i18n/zh.json b/webui/i18n/zh.jsonindex ead5526c..c6c6dfaf 100644--- a/webui/i18n/zh.json+++ b/webui/i18n/zh.json@@ -603,6 +603,13 @@"kimi_code.oauth.region_mismatch": "当前凭证属于「{authorized}」区域,但所选 API Platform 为「{selected}」。请求将按凭证区域「{authorized}」发出;如需切换区域,请重新登录。","kimi_code.oauth.network_error": "无法连接 Kimi 授权服务(网络错误)。请检查网络连接后重新发起登录。","kimi_code.oauth.changed": "登录状态已在其他页面变更,本次授权已停止。请按需重新登录。",- "kimi_code.oauth.poll_retry": "检查授权状态时网络异常,正在自动重试……"+ "kimi_code.oauth.poll_retry": "检查授权状态时网络异常,正在自动重试……",+ "Diagnostic Logging": "诊断日志",+ "Diagnostic Logging Help": "立即调整当前服务的日志,设置对所有浏览器会话生效。",+ "Log Level": "日志等级",+ "Trace API Requests": "记录 API 请求参数",+ "Trace API Requests Help": "独立于日志等级,默认关闭。记录脱敏参数、状态和耗时;提示词可能可见。音视频和响应正文不记录。排查结束后请关闭。",+ "Apply Logging Settings": "应用日志设置",+ "Logging Settings Applied": "日志设置已在当前服务生效。"}}