gateway/modules/shared/debugLogger.py

79 lines
3 KiB
Python

"""
Simple debug logger for AI prompts and responses.
Writes files chronologically to the configured log directory with sequential numbering.
"""
import os
from datetime import datetime, UTC
from typing import List, Optional
from modules.shared.configuration import APP_CONFIG
def _getDebugDir() -> str:
"""Get the debug directory path from configuration."""
# Get log directory from config (same as used by main logging system)
logDir = APP_CONFIG.get("APP_LOGGING_LOG_DIR", "./")
if not os.path.isabs(logDir):
# If relative path, make it relative to the gateway directory
gatewayDir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
logDir = os.path.join(gatewayDir, logDir)
# Create debug subdirectory within the log directory
debugDir = os.path.join(logDir, 'debug')
return debugDir
def _getNextSequenceNumber() -> int:
"""Get the next sequence number by counting existing files."""
debugDir = _getDebugDir()
if not os.path.exists(debugDir):
return 1
# Count existing numbered files
files = [f for f in os.listdir(debugDir) if f.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))]
return len(files) + 1
def writeDebugFile(content: str, fileType: str, documents: Optional[List] = None) -> None:
"""
Write debug content to a file with sequential numbering.
Writes the content as-is since it's already the final integrated prompt.
Includes document list labels for tracing enhancement.
Args:
content: The main content to write (already integrated)
fileType: Type of file (e.g., 'prompt_final', 'response')
documents: Optional list of documents for tracing
"""
try:
debugDir = _getDebugDir()
os.makedirs(debugDir, exist_ok=True)
seqNum = _getNextSequenceNumber()
ts = datetime.now(UTC).strftime('%Y%m%d-%H%M%S')
# Add 3-digit sequence number for uniqueness
tsWithSeq = f"{ts}-{seqNum:03d}"
filename = f"{tsWithSeq}-{fileType}.txt"
filepath = os.path.join(debugDir, filename)
# Build content with document tracing
debug_content = content
# Add document list labels for tracing enhancement
if documents:
debug_content += "\n\n=== DOCUMENT LIST FOR TRACING ===\n"
for i, doc in enumerate(documents):
if hasattr(doc, 'fileName'):
debug_content += f"Document {i+1}: {doc.fileName} ({doc.mimeType})\n"
elif hasattr(doc, 'fileId'):
debug_content += f"Document {i+1}: {doc.fileId} ({getattr(doc, 'mimeType', 'unknown')})\n"
else:
debug_content += f"Document {i+1}: {str(doc)[:100]}...\n"
# Write the content with document tracing
with open(filepath, 'w', encoding='utf-8') as f:
f.write(debug_content)
except Exception as e:
# Silent fail - don't break the main flow
pass