schematic-drawing / backend /logging_utils.py
samu's picture
fix logging
9183203
raw
history blame
2.48 kB
import logging
from datetime import datetime
import json
from pathlib import Path
import os
from typing import Optional
# Configure logging
# Use /tmp for logs in production (e.g. Hugging Face Spaces) or local logs dir in development
log_dir = Path("/tmp/schematic_ai_logs") if os.environ.get("SPACE_ID") else Path(__file__).parent.parent / "logs"
log_dir.mkdir(exist_ok=True, parents=True)
# Configure file handler for general logs
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler() # Always log to console
]
)
# Only add file handler if we can write to the directory
try:
if os.access(log_dir, os.W_OK):
file_handler = logging.FileHandler(log_dir / "app.log")
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logging.getLogger().addHandler(file_handler)
except Exception as e:
logging.warning(f"Could not set up file logging: {e}")
def log_category_usage(category: Optional[str] = None):
"""Log the usage of a category."""
if not os.access(log_dir, os.W_OK):
logging.warning("Log directory is not writable, skipping category usage logging")
return
stats_file = log_dir / "category_stats.json"
try:
if stats_file.exists():
with open(stats_file, 'r') as f:
stats = json.load(f)
else:
stats = {}
# Initialize or increment category count
category = category or "default"
if category in stats:
stats[category] += 1
else:
stats[category] = 1
# Save updated stats
with open(stats_file, 'w') as f:
json.dump(stats, f, indent=4)
except Exception as e:
logging.error(f"Error logging category usage: {e}")
def get_category_statistics():
"""Get the usage statistics for all categories."""
if not os.access(log_dir, os.W_OK):
logging.warning("Log directory is not writable, cannot read category statistics")
return {}
stats_file = log_dir / "category_stats.json"
try:
if stats_file.exists():
with open(stats_file, 'r') as f:
return json.load(f)
return {}
except Exception as e:
logging.error(f"Error reading category statistics: {e}")
return {}