================================================================================ GMAIL CLEANUP - CHALLENGE 3 SOLUTION Chapter 6: Generalization & Extension Challenge: Production-Ready Utility ================================================================================ PROBLEM: Build production-ready tool with: 1. Scheduling (APScheduler) 2. Logging to file 3. Error notifications (email) 4. Comprehensive documentation SOLUTION: ================================================================================ File: cleanup_production.py import logging from datetime import datetime from pathlib import Path from apscheduler.schedulers.background import BackgroundScheduler from gmail_utils import get_gmail_service, GmailCleanup from config import Config # Setup logging LOG_FILE = Path(__file__).parent / "cleanup.log" logging.basicConfig( filename=LOG_FILE, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) def send_error_email(error: str): """Send error notification (requires email setup).""" # Would integrate with Gmail API to send error report logger.error(f"ERROR: {error}") def run_cleanup(): """Run cleanup workflow with logging.""" try: logger.info("Starting cleanup routine") config = Config() if not config.validate(): logger.error("Configuration invalid") return service = get_gmail_service() cleanup = GmailCleanup(service, config) # Cleanup old emails logger.info(f"Finding emails older than {config.days_old} days") emails = cleanup.find_old_emails(config.days_old) if emails: for email in emails: cleanup.delete_email(email['id']) logger.info(f"Deleted {len(emails)} emails") # Log final stats stats = cleanup.get_stats() logger.info(f"CLEANUP COMPLETE: Deleted {stats['deleted']}, Freed {stats['storage_freed_mb']} MB") except Exception as e: logger.error(f"Unexpected error: {e}") send_error_email(str(e)) def schedule_cleanup(): """Schedule cleanup to run daily at 2 AM.""" scheduler = BackgroundScheduler() # Run daily at 2 AM scheduler.add_job(run_cleanup, 'cron', hour=2, minute=0) scheduler.start() logger.info("Scheduler started: Daily cleanup at 2:00 AM") try: import time while True: time.sleep(1) except KeyboardInterrupt: scheduler.shutdown() logger.info("Scheduler stopped") if __name__ == "__main__": # For testing: run once # run_cleanup() # For production: schedule daily schedule_cleanup() SETUP FOR PRODUCTION ================================================================================ 1. Install APScheduler: pip install apscheduler 2. Create cleanup_production.py with code above 3. Run in background: nohup python cleanup_production.py & 4. Monitor logs: tail -f cleanup.log 5. View scheduled cleanups: grep "CLEANUP COMPLETE" cleanup.log EXAMPLE LOG ================================================================================ 2026-06-30 02:00:00,123 - INFO - Starting cleanup routine 2026-06-30 02:00:05,456 - INFO - Finding emails older than 365 days 2026-06-30 02:00:15,789 - INFO - Deleted 45 emails 2026-06-30 02:00:18,012 - INFO - CLEANUP COMPLETE: Deleted 45, Freed 125.50 MB 2026-07-01 02:00:00,123 - INFO - Starting cleanup routine ... PRODUCTION IMPROVEMENTS ================================================================================ ✅ Logging instead of print() ✅ Scheduled execution (daily) ✅ Error handling and notifications ✅ Audit trail (log file) ✅ Monitoring capability ✅ Graceful shutdown NEXT STEPS ================================================================================ ✅ Add email notifications ✅ Add dashboard to view stats ✅ Add database logging ✅ Add multi-account support ✅ Add rollback capability You've built a production-ready utility! ================================================================================