Log API response details to log.txt
(
self,
status_code: int,
headers: Dict[str, str],
body: Any,
duration_ms: Optional[float] = None
)
| 160 | self.logger.error(f"Error logging request: {e}") |
| 161 | |
| 162 | def log_response( |
| 163 | self, |
| 164 | status_code: int, |
| 165 | headers: Dict[str, str], |
| 166 | body: Any, |
| 167 | duration_ms: Optional[float] = None |
| 168 | ): |
| 169 | """Log API response details to log.txt""" |
| 170 | |
| 171 | if not config.debug_enabled or not config.debug_log_responses: |
| 172 | return |
| 173 | |
| 174 | try: |
| 175 | self._write_separator() |
| 176 | self.logger.info(f"🟢 [RESPONSE] {self._format_timestamp()}") |
| 177 | self._write_separator("-") |
| 178 | |
| 179 | # Status |
| 180 | status_emoji = "✅" if 200 <= status_code < 300 else "❌" |
| 181 | self.logger.info(f"Status: {status_code} {status_emoji}") |
| 182 | |
| 183 | # Duration |
| 184 | if duration_ms is not None: |
| 185 | self.logger.info(f"Duration: {duration_ms:.2f}ms") |
| 186 | |
| 187 | # Headers |
| 188 | self.logger.info("\n📋 Response Headers:") |
| 189 | for key, value in headers.items(): |
| 190 | self.logger.info(f" {key}: {value}") |
| 191 | |
| 192 | # Body |
| 193 | self.logger.info("\n📦 Response Body:") |
| 194 | if isinstance(body, (dict, list)): |
| 195 | # 对大字段进行截断处理 |
| 196 | body_to_log = self._truncate_large_fields(body) |
| 197 | body_str = json.dumps(body_to_log, indent=2, ensure_ascii=False) |
| 198 | self.logger.info(body_str) |
| 199 | elif isinstance(body, str): |
| 200 | # Try to parse as JSON |
| 201 | try: |
| 202 | parsed = json.loads(body) |
| 203 | # 对大字段进行截断处理 |
| 204 | parsed = self._truncate_large_fields(parsed) |
| 205 | body_str = json.dumps(parsed, indent=2, ensure_ascii=False) |
| 206 | self.logger.info(body_str) |
| 207 | except: |
| 208 | # Not JSON, log as text (limit length) |
| 209 | if len(body) > 2000: |
| 210 | self.logger.info(f"{body[:2000]}... (truncated)") |
| 211 | else: |
| 212 | self.logger.info(body) |
| 213 | else: |
| 214 | self.logger.info(str(body)) |
| 215 | |
| 216 | self._write_separator() |
| 217 | self.logger.info("") # Empty line |
| 218 | |
| 219 | except Exception as e: |
no test coverage detected