Skip to content

Commit 64f999f

Browse files
bigcat88gmaOCR
authored andcommitted
feat(api-nodes, pylint): use lazy formatting in logging functions (comfyanonymous#10248)
1 parent 855359f commit 64f999f

File tree

9 files changed

+50
-46
lines changed

9 files changed

+50
-46
lines changed

comfy_api_nodes/apinode_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,7 @@ async def upload_video_to_comfyapi(
431431
f"Video duration ({actual_duration:.2f}s) exceeds the maximum allowed ({max_duration}s)."
432432
)
433433
except Exception as e:
434-
logging.error(f"Error getting video duration: {e}")
434+
logging.error("Error getting video duration: %s", str(e))
435435
raise ValueError(f"Could not verify video duration from source: {e}") from e
436436

437437
upload_mime_type = f"video/{container.value.lower()}"

comfy_api_nodes/apis/client.py

Lines changed: 32 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -359,10 +359,10 @@ async def request(
359359
if params:
360360
params = {k: v for k, v in params.items() if v is not None} # aiohttp fails to serialize None values
361361

362-
logging.debug(f"[DEBUG] Request Headers: {request_headers}")
363-
logging.debug(f"[DEBUG] Files: {files}")
364-
logging.debug(f"[DEBUG] Params: {params}")
365-
logging.debug(f"[DEBUG] Data: {data}")
362+
logging.debug("[DEBUG] Request Headers: %s", request_headers)
363+
logging.debug("[DEBUG] Files: %s", files)
364+
logging.debug("[DEBUG] Params: %s", params)
365+
logging.debug("[DEBUG] Data: %s", data)
366366

367367
if content_type == "application/x-www-form-urlencoded":
368368
payload_args = self._create_urlencoded_form_data_args(data or {}, request_headers)
@@ -592,9 +592,9 @@ async def _handle_http_error(
592592
error_message=f"HTTP Error {exc.status}",
593593
)
594594

595-
logging.debug(f"[DEBUG] API Error: {user_friendly} (Status: {status_code})")
595+
logging.debug("[DEBUG] API Error: %s (Status: %s)", user_friendly, status_code)
596596
if response_content:
597-
logging.debug(f"[DEBUG] Response content: {response_content}")
597+
logging.debug("[DEBUG] Response content: %s", response_content)
598598

599599
# Retry if eligible
600600
if status_code in self.retry_status_codes and retry_count < self.max_retries:
@@ -738,11 +738,9 @@ async def execute(self, client: Optional[ApiClient] = None) -> R:
738738
if isinstance(v, Enum):
739739
request_dict[k] = v.value
740740

741-
logging.debug(
742-
f"[DEBUG] API Request: {self.endpoint.method.value} {self.endpoint.path}"
743-
)
744-
logging.debug(f"[DEBUG] Request Data: {json.dumps(request_dict, indent=2)}")
745-
logging.debug(f"[DEBUG] Query Params: {self.endpoint.query_params}")
741+
logging.debug("[DEBUG] API Request: %s %s", self.endpoint.method.value, self.endpoint.path)
742+
logging.debug("[DEBUG] Request Data: %s", json.dumps(request_dict, indent=2))
743+
logging.debug("[DEBUG] Query Params: %s", self.endpoint.query_params)
746744

747745
response_json = await client.request(
748746
self.endpoint.method.value,
@@ -757,11 +755,11 @@ async def execute(self, client: Optional[ApiClient] = None) -> R:
757755
logging.debug("=" * 50)
758756
logging.debug("[DEBUG] RESPONSE DETAILS:")
759757
logging.debug("[DEBUG] Status Code: 200 (Success)")
760-
logging.debug(f"[DEBUG] Response Body: {json.dumps(response_json, indent=2)}")
758+
logging.debug("[DEBUG] Response Body: %s", json.dumps(response_json, indent=2))
761759
logging.debug("=" * 50)
762760

763761
parsed_response = self.endpoint.response_model.model_validate(response_json)
764-
logging.debug(f"[DEBUG] Parsed Response: {parsed_response}")
762+
logging.debug("[DEBUG] Parsed Response: %s", parsed_response)
765763
return parsed_response
766764
finally:
767765
if owns_client:
@@ -877,18 +875,21 @@ async def _poll_until_complete(self, client: ApiClient) -> R:
877875
status = TaskStatus.PENDING
878876
for poll_count in range(1, self.max_poll_attempts + 1):
879877
try:
880-
logging.debug(f"[DEBUG] Polling attempt #{poll_count}")
878+
logging.debug("[DEBUG] Polling attempt #%s", poll_count)
881879

882880
request_dict = (
883881
None if self.request is None else self.request.model_dump(exclude_none=True)
884882
)
885883

886884
if poll_count == 1:
887885
logging.debug(
888-
f"[DEBUG] Poll Request: {self.poll_endpoint.method.value} {self.poll_endpoint.path}"
886+
"[DEBUG] Poll Request: %s %s",
887+
self.poll_endpoint.method.value,
888+
self.poll_endpoint.path,
889889
)
890890
logging.debug(
891-
f"[DEBUG] Poll Request Data: {json.dumps(request_dict, indent=2) if request_dict else 'None'}"
891+
"[DEBUG] Poll Request Data: %s",
892+
json.dumps(request_dict, indent=2) if request_dict else "None",
892893
)
893894

894895
# Query task status
@@ -903,7 +904,7 @@ async def _poll_until_complete(self, client: ApiClient) -> R:
903904

904905
# Check if task is complete
905906
status = self._check_task_status(response_obj)
906-
logging.debug(f"[DEBUG] Task Status: {status}")
907+
logging.debug("[DEBUG] Task Status: %s", status)
907908

908909
# If progress extractor is provided, extract progress
909910
if self.progress_extractor:
@@ -917,15 +918,15 @@ async def _poll_until_complete(self, client: ApiClient) -> R:
917918
result_url = self.result_url_extractor(response_obj)
918919
if result_url:
919920
message = f"Result URL: {result_url}"
920-
logging.debug(f"[DEBUG] {message}")
921+
logging.debug("[DEBUG] %s", message)
921922
self._display_text_on_node(message)
922923
self.final_response = response_obj
923924
if self.progress_extractor:
924925
progress.update(100)
925926
return self.final_response
926927
if status == TaskStatus.FAILED:
927928
message = f"Task failed: {json.dumps(resp)}"
928-
logging.error(f"[DEBUG] {message}")
929+
logging.error("[DEBUG] %s", message)
929930
raise Exception(message)
930931
logging.debug("[DEBUG] Task still pending, continuing to poll...")
931932
# Task pending – wait
@@ -939,7 +940,12 @@ async def _poll_until_complete(self, client: ApiClient) -> R:
939940
raise Exception(
940941
f"Polling aborted after {consecutive_errors} network errors: {str(e)}"
941942
) from e
942-
logging.warning("Network error (%s/%s): %s", consecutive_errors, max_consecutive_errors, str(e))
943+
logging.warning(
944+
"Network error (%s/%s): %s",
945+
consecutive_errors,
946+
max_consecutive_errors,
947+
str(e),
948+
)
943949
await asyncio.sleep(self.poll_interval)
944950
except Exception as e:
945951
# For other errors, increment count and potentially abort
@@ -949,10 +955,13 @@ async def _poll_until_complete(self, client: ApiClient) -> R:
949955
f"Polling aborted after {consecutive_errors} consecutive errors: {str(e)}"
950956
) from e
951957

952-
logging.error(f"[DEBUG] Polling error: {str(e)}")
958+
logging.error("[DEBUG] Polling error: %s", str(e))
953959
logging.warning(
954-
f"Error during polling (attempt {poll_count}/{self.max_poll_attempts}): {str(e)}. "
955-
f"Will retry in {self.poll_interval} seconds."
960+
"Error during polling (attempt %s/%s): %s. Will retry in %s seconds.",
961+
poll_count,
962+
self.max_poll_attempts,
963+
str(e),
964+
self.poll_interval,
956965
)
957966
await asyncio.sleep(self.poll_interval)
958967

comfy_api_nodes/apis/request_logger.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def get_log_directory():
2121
try:
2222
os.makedirs(log_dir, exist_ok=True)
2323
except Exception as e:
24-
logger.error(f"Error creating API log directory {log_dir}: {e}")
24+
logger.error("Error creating API log directory %s: %s", log_dir, str(e))
2525
# Fallback to base temp directory if sub-directory creation fails
2626
return base_temp_dir
2727
return log_dir
@@ -122,9 +122,9 @@ def log_request_response(
122122
try:
123123
with open(filepath, "w", encoding="utf-8") as f:
124124
f.write("\n".join(log_content))
125-
logger.debug(f"API log saved to: {filepath}")
125+
logger.debug("API log saved to: %s", filepath)
126126
except Exception as e:
127-
logger.error(f"Error writing API log to {filepath}: {e}")
127+
logger.error("Error writing API log to %s: %s", filepath, str(e))
128128

129129

130130
if __name__ == '__main__':

comfy_api_nodes/nodes_kling.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -296,15 +296,15 @@ def validate_video_result_response(response) -> None:
296296
"""Validates that the Kling task result contains a video."""
297297
if not is_valid_video_response(response):
298298
error_msg = f"Kling task {response.data.task_id} succeeded but no video data found in response."
299-
logging.error(f"Error: {error_msg}.\nResponse: {response}")
299+
logging.error("Error: %s.\nResponse: %s", error_msg, response)
300300
raise Exception(error_msg)
301301

302302

303303
def validate_image_result_response(response) -> None:
304304
"""Validates that the Kling task result contains an image."""
305305
if not is_valid_image_response(response):
306306
error_msg = f"Kling task {response.data.task_id} succeeded but no image data found in response."
307-
logging.error(f"Error: {error_msg}.\nResponse: {response}")
307+
logging.error("Error: %s.\nResponse: %s", error_msg, response)
308308
raise Exception(error_msg)
309309

310310

comfy_api_nodes/nodes_minimax.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -500,7 +500,7 @@ async def execute(
500500
raise Exception(
501501
f"No video was found in the response. Full response: {file_result.model_dump()}"
502502
)
503-
logging.info(f"Generated video URL: {file_url}")
503+
logging.info("Generated video URL: %s", file_url)
504504
if cls.hidden.unique_id:
505505
if hasattr(file_result.file, "backup_download_url"):
506506
message = f"Result URL: {file_url}\nBackup URL: {file_result.file.backup_download_url}"

comfy_api_nodes/nodes_moonvalley.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -237,7 +237,7 @@ def trim_video(video: VideoInput, duration_sec: float) -> VideoInput:
237237
audio_stream = None
238238

239239
for stream in input_container.streams:
240-
logging.info(f"Found stream: type={stream.type}, class={type(stream)}")
240+
logging.info("Found stream: type=%s, class=%s", stream.type, type(stream))
241241
if isinstance(stream, av.VideoStream):
242242
# Create output video stream with same parameters
243243
video_stream = output_container.add_stream(
@@ -247,7 +247,7 @@ def trim_video(video: VideoInput, duration_sec: float) -> VideoInput:
247247
video_stream.height = stream.height
248248
video_stream.pix_fmt = "yuv420p"
249249
logging.info(
250-
f"Added video stream: {stream.width}x{stream.height} @ {stream.average_rate}fps"
250+
"Added video stream: %sx%s @ %sfps", stream.width, stream.height, stream.average_rate
251251
)
252252
elif isinstance(stream, av.AudioStream):
253253
# Create output audio stream with same parameters
@@ -256,9 +256,7 @@ def trim_video(video: VideoInput, duration_sec: float) -> VideoInput:
256256
)
257257
audio_stream.sample_rate = stream.sample_rate
258258
audio_stream.layout = stream.layout
259-
logging.info(
260-
f"Added audio stream: {stream.sample_rate}Hz, {stream.channels} channels"
261-
)
259+
logging.info("Added audio stream: %sHz, %s channels", stream.sample_rate, stream.channels)
262260

263261
# Calculate target frame count that's divisible by 16
264262
fps = input_container.streams.video[0].average_rate
@@ -288,9 +286,7 @@ def trim_video(video: VideoInput, duration_sec: float) -> VideoInput:
288286
for packet in video_stream.encode():
289287
output_container.mux(packet)
290288

291-
logging.info(
292-
f"Encoded {frame_count} video frames (target: {target_frames})"
293-
)
289+
logging.info("Encoded %s video frames (target: %s)", frame_count, target_frames)
294290

295291
# Decode and re-encode audio frames
296292
if audio_stream:
@@ -308,7 +304,7 @@ def trim_video(video: VideoInput, duration_sec: float) -> VideoInput:
308304
for packet in audio_stream.encode():
309305
output_container.mux(packet)
310306

311-
logging.info(f"Encoded {audio_frame_count} audio frames")
307+
logging.info("Encoded %s audio frames", audio_frame_count)
312308

313309
# Close containers
314310
output_container.close()

comfy_api_nodes/nodes_rodin.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -172,16 +172,16 @@ async def create_generate_task(
172172
logging.info("[ Rodin3D API - Submit Jobs ] Submit Generate Task Success!")
173173
subscription_key = response.jobs.subscription_key
174174
task_uuid = response.uuid
175-
logging.info(f"[ Rodin3D API - Submit Jobs ] UUID: {task_uuid}")
175+
logging.info("[ Rodin3D API - Submit Jobs ] UUID: %s", task_uuid)
176176
return task_uuid, subscription_key
177177

178178

179179
def check_rodin_status(response: Rodin3DCheckStatusResponse) -> str:
180180
all_done = all(job.status == JobStatus.Done for job in response.jobs)
181181
status_list = [str(job.status) for job in response.jobs]
182-
logging.info(f"[ Rodin3D API - CheckStatus ] Generate Status: {status_list}")
182+
logging.info("[ Rodin3D API - CheckStatus ] Generate Status: %s", status_list)
183183
if any(job.status == JobStatus.Failed for job in response.jobs):
184-
logging.error(f"[ Rodin3D API - CheckStatus ] Generate Failed: {status_list}, Please try again.")
184+
logging.error("[ Rodin3D API - CheckStatus ] Generate Failed: %s, Please try again.", status_list)
185185
raise Exception("[ Rodin3D API ] Generate Failed, Please Try again.")
186186
if all_done:
187187
return "DONE"
@@ -235,7 +235,7 @@ async def download_files(url_list, task_uuid):
235235
file_path = os.path.join(save_path, file_name)
236236
if file_path.endswith(".glb"):
237237
model_file_path = file_path
238-
logging.info(f"[ Rodin3D API - download_files ] Downloading file: {file_path}")
238+
logging.info("[ Rodin3D API - download_files ] Downloading file: %s", file_path)
239239
max_retries = 5
240240
for attempt in range(max_retries):
241241
try:
@@ -246,7 +246,7 @@ async def download_files(url_list, task_uuid):
246246
f.write(chunk)
247247
break
248248
except Exception as e:
249-
logging.info(f"[ Rodin3D API - download_files ] Error downloading {file_path}:{e}")
249+
logging.info("[ Rodin3D API - download_files ] Error downloading %s:%s", file_path, str(e))
250250
if attempt < max_retries - 1:
251251
logging.info("Retrying...")
252252
await asyncio.sleep(2)

comfy_api_nodes/nodes_veo2.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ async def execute(
215215
initial_response = await initial_operation.execute()
216216
operation_name = initial_response.name
217217

218-
logging.info(f"Veo generation started with operation name: {operation_name}")
218+
logging.info("Veo generation started with operation name: %s", operation_name)
219219

220220
# Define status extractor function
221221
def status_extractor(response):

pyproject.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,6 @@ messages_control.disable = [
6161
# next warnings should be fixed in future
6262
"bad-classmethod-argument", # Class method should have 'cls' as first argument
6363
"wrong-import-order", # Standard imports should be placed before third party imports
64-
"logging-fstring-interpolation", # Use lazy % formatting in logging functions
6564
"ungrouped-imports",
6665
"unnecessary-pass",
6766
"unnecessary-lambda-assignment",

0 commit comments

Comments
 (0)