Merge pull request #14 from ComfyAssets/logger-unicode

Logger unicode
This commit is contained in:
Vito
2025-05-28 09:18:49 -07:00
committed by GitHub
4 changed files with 43 additions and 40 deletions
+1 -1
View File
@@ -69,4 +69,4 @@ except Exception as e:
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
log_message("✅ PromptManager custom node loaded successfully!")
log_message("[SUCCESS] PromptManager custom node loaded successfully!")
+7 -7
View File
@@ -17,31 +17,31 @@ try:
from utils.prompt_tracker import PromptTracker
from utils.image_monitor import ImageMonitor
print("🔄 Restarting PromptManager Gallery System...")
print("[RESTART] Restarting PromptManager Gallery System...")
# Initialize components
db = PromptDatabase()
tracker = PromptTracker(db)
monitor = ImageMonitor(db, tracker)
print("✅ Components initialized successfully")
print("[SUCCESS] Components initialized successfully")
# Test image monitoring directories
status = monitor.get_status()
print(f"📁 Monitoring status: {status}")
print(f"[INFO] Monitoring status: {status}")
# Start monitoring
monitor.start_monitoring()
print("✅ Image monitoring restarted")
print("[SUCCESS] Image monitoring restarted")
print("\n🎉 Gallery system restart completed!")
print("\n[READY] Gallery system restart completed!")
print("Generate some images now to test the automatic linking.")
except ImportError as e:
print(f"❌ Import error: {e}")
print(f"[ERROR] Import error: {e}")
print("Make sure you're running this from the PromptManager directory")
except Exception as e:
print(f"❌ Error: {e}")
print(f"[ERROR] Error: {e}")
import traceback
traceback.print_exc()
+27 -27
View File
@@ -20,7 +20,7 @@ class GalleryDiagnostics:
def run_full_diagnostic(self) -> Dict[str, Any]:
"""Run a complete diagnostic check."""
self.logger.info("\n" + "="*60)
self.logger.info("🔍 PROMPTMANAGER GALLERY DIAGNOSTICS")
self.logger.info("[DIAG] PROMPTMANAGER GALLERY DIAGNOSTICS")
self.logger.info("="*60)
results = {
@@ -32,11 +32,11 @@ class GalleryDiagnostics:
}
self.logger.info("\n" + "="*60)
self.logger.info("📋 DIAGNOSTIC SUMMARY")
self.logger.info("[SUMMARY] DIAGNOSTIC SUMMARY")
self.logger.info("="*60)
for category, result in results.items():
status = "✅ PASS" if result['status'] == 'ok' else "❌ FAIL"
status = "[PASS] PASS" if result['status'] == 'ok' else "[FAIL] FAIL"
self.logger.info(f"{category.upper():<20} {status}")
if result['status'] != 'ok':
self.logger.warning(f" Issue: {result['message']}")
@@ -46,7 +46,7 @@ class GalleryDiagnostics:
def check_database(self) -> Dict[str, Any]:
"""Check database connection and structure."""
self.logger.info("\n🗄️ Checking Database...")
self.logger.info("\n[DB] Checking Database...")
try:
if not os.path.exists(self.db_path):
@@ -61,7 +61,7 @@ class GalleryDiagnostics:
# Check prompts table
cursor = conn.execute("SELECT COUNT(*) as count FROM prompts")
prompt_count = cursor.fetchone()['count']
self.logger.info(f" 📝 Prompts in database: {prompt_count}")
self.logger.info(f" [NOTE] Prompts in database: {prompt_count}")
# Check if generated_images table exists
cursor = conn.execute("""
@@ -70,7 +70,7 @@ class GalleryDiagnostics:
""")
has_images_table = cursor.fetchone() is not None
self.logger.info(f" 🖼️ Images table exists: {has_images_table}")
self.logger.info(f" [IMG] Images table exists: {has_images_table}")
return {
'status': 'ok',
@@ -86,7 +86,7 @@ class GalleryDiagnostics:
def check_images_table(self) -> Dict[str, Any]:
"""Check the generated_images table specifically."""
self.logger.info("\n🖼️ Checking Images Table...")
self.logger.info("\n[IMG] Checking Images Table...")
try:
with sqlite3.connect(self.db_path) as conn:
@@ -107,7 +107,7 @@ class GalleryDiagnostics:
# Check image records
cursor = conn.execute("SELECT COUNT(*) as count FROM generated_images")
image_count = cursor.fetchone()['count']
self.logger.info(f" 📊 Images in database: {image_count}")
self.logger.info(f" [STATS] Images in database: {image_count}")
# Get recent images
cursor = conn.execute("""
@@ -119,7 +119,7 @@ class GalleryDiagnostics:
""")
recent_images = [dict(row) for row in cursor.fetchall()]
self.logger.info(f" 🕒 Recent images: {len(recent_images)}")
self.logger.info(f" [TIME] Recent images: {len(recent_images)}")
for img in recent_images:
self.logger.info(f" - {img['filename']} -> Prompt {img['prompt_id']}")
@@ -137,12 +137,12 @@ class GalleryDiagnostics:
def check_file_system(self) -> Dict[str, Any]:
"""Check file system and permissions."""
self.logger.info("\n📁 Checking File System...")
self.logger.info("\n[DIR] Checking File System...")
try:
# Check current directory
current_dir = os.getcwd()
self.logger.info(f" 📂 Current directory: {current_dir}")
self.logger.info(f" [FOLDER] Current directory: {current_dir}")
# Check if we can write to current directory
test_file = "test_write.tmp"
@@ -154,7 +154,7 @@ class GalleryDiagnostics:
except:
can_write = False
self.logger.info(f" ✏️ Can write to directory: {can_write}")
self.logger.info(f" [EDIT] Can write to directory: {can_write}")
return {
'status': 'ok',
@@ -170,7 +170,7 @@ class GalleryDiagnostics:
def check_comfyui_output(self) -> Dict[str, Any]:
"""Check ComfyUI output directories."""
self.logger.info("\n🎨 Checking ComfyUI Output...")
self.logger.info("\n[STYLE] Checking ComfyUI Output...")
output_dirs = []
@@ -188,16 +188,16 @@ class GalleryDiagnostics:
abs_path = os.path.abspath(dir_path)
if os.path.exists(abs_path):
output_dirs.append(abs_path)
self.logger.info(f" 📁 Found output dir: {abs_path}")
self.logger.info(f" [DIR] Found output dir: {abs_path}")
# Count images in this directory
try:
image_files = []
for ext in ['.png', '.jpg', '.jpeg', '.webp']:
image_files.extend(Path(abs_path).rglob(f'*{ext}'))
self.logger.info(f" 🖼️ Images found: {len(image_files)}")
self.logger.info(f" [IMG] Images found: {len(image_files)}")
except Exception as e:
self.logger.error(f" ❌ Error scanning: {e}")
self.logger.error(f" [FAIL] Error scanning: {e}")
# Try ComfyUI's folder_paths
try:
@@ -205,9 +205,9 @@ class GalleryDiagnostics:
comfyui_output = folder_paths.get_output_directory()
if comfyui_output and comfyui_output not in output_dirs:
output_dirs.append(comfyui_output)
self.logger.info(f" 📁 ComfyUI output dir: {comfyui_output}")
self.logger.info(f" [DIR] ComfyUI output dir: {comfyui_output}")
except ImportError:
self.logger.warning(" ⚠️ ComfyUI folder_paths not available")
self.logger.warning(" [WARN] ComfyUI folder_paths not available")
return {
'status': 'ok' if output_dirs else 'warning',
@@ -217,7 +217,7 @@ class GalleryDiagnostics:
def check_dependencies(self) -> Dict[str, Any]:
"""Check required dependencies."""
self.logger.info("\n📦 Checking Dependencies...")
self.logger.info("\n[PKG] Checking Dependencies...")
dependencies = {
'watchdog': False,
@@ -229,25 +229,25 @@ class GalleryDiagnostics:
try:
import watchdog
dependencies['watchdog'] = True
self.logger.info(f" ✅ watchdog: {watchdog.__version__}")
self.logger.info(f" [PASS] watchdog: {watchdog.__version__}")
except ImportError:
self.logger.error(" ❌ watchdog: NOT INSTALLED")
self.logger.error(" [FAIL] watchdog: NOT INSTALLED")
# Check PIL
try:
from PIL import Image
dependencies['PIL'] = True
self.logger.info(f" ✅ PIL (Pillow): Available")
self.logger.info(f" [PASS] PIL (Pillow): Available")
except ImportError:
self.logger.error(" ❌ PIL (Pillow): NOT AVAILABLE")
self.logger.error(" [FAIL] PIL (Pillow): NOT AVAILABLE")
# Check sqlite3
try:
import sqlite3
dependencies['sqlite3'] = True
self.logger.info(f" ✅ sqlite3: {sqlite3.sqlite_version}")
self.logger.info(f" [PASS] sqlite3: {sqlite3.sqlite_version}")
except ImportError:
self.logger.error(" ❌ sqlite3: NOT AVAILABLE")
self.logger.error(" [FAIL] sqlite3: NOT AVAILABLE")
all_deps_ok = all(dependencies.values())
@@ -259,7 +259,7 @@ class GalleryDiagnostics:
def create_test_image_link(self, prompt_id: int, test_image_path: str = None) -> Dict[str, Any]:
"""Create a test image link to verify the system works."""
self.logger.info(f"\n🧪 Creating test image link for prompt {prompt_id}...")
self.logger.info(f"\n[TEST] Creating test image link for prompt {prompt_id}...")
try:
# Import database operations
@@ -292,7 +292,7 @@ class GalleryDiagnostics:
metadata=test_metadata
)
self.logger.info(f" ✅ Test image linked with ID: {image_id}")
self.logger.info(f" [PASS] Test image linked with ID: {image_id}")
return {
'status': 'ok',
+8 -5
View File
@@ -88,13 +88,15 @@ class PromptManagerLogger:
console_handler.setFormatter(formatter)
self.logger.addHandler(console_handler)
# File handler with rotation
# File handler with rotation and safe encoding for Windows
if self.config['file_logging']:
log_file = self.log_dir / "prompt_manager.log"
file_handler = logging.handlers.RotatingFileHandler(
log_file,
maxBytes=self.config['max_file_size'],
backupCount=self.config['backup_count']
backupCount=self.config['backup_count'],
encoding='utf-8',
errors='replace' # Replace problematic characters instead of crashing
)
file_handler.setFormatter(formatter)
self.logger.addHandler(file_handler)
@@ -196,7 +198,8 @@ class PromptManagerLogger:
raise ValueError("Invalid log file path")
try:
with open(log_file, 'r', encoding='utf-8') as f:
# Use UTF-8 encoding with error handling for Windows compatibility
with open(log_file, 'r', encoding='utf-8', errors='replace') as f:
all_lines = f.readlines()
return all_lines[-lines:] if lines > 0 else all_lines
except Exception as e:
@@ -213,8 +216,8 @@ class PromptManagerLogger:
for log_file in self.log_dir.glob("prompt_manager.log*"):
try:
if log_file.name == 'prompt_manager.log':
# For main log file, just clear it
with open(log_file, 'w') as f:
# For main log file, just clear it with safe encoding
with open(log_file, 'w', encoding='utf-8', errors='replace') as f:
f.write("")
else:
# For rotated files, delete them