Shane 7 months ago
parent cd62ca9a1f
commit ebef8f35d5
  1. 57
      foodie_engagement_tweet.py

@ -21,6 +21,7 @@ from dotenv import load_dotenv
load_dotenv() load_dotenv()
# Define constants
REFERENCE_DATE_FILE = ENGAGEMENT_REFERENCE_DATE_FILE REFERENCE_DATE_FILE = ENGAGEMENT_REFERENCE_DATE_FILE
LOCK_FILE = "/home/shane/foodie_automator/locks/foodie_engagement_tweet.lock" LOCK_FILE = "/home/shane/foodie_automator/locks/foodie_engagement_tweet.lock"
LOG_FILE = "/home/shane/foodie_automator/logs/foodie_engagement_tweet.log" LOG_FILE = "/home/shane/foodie_automator/logs/foodie_engagement_tweet.log"
@ -31,27 +32,32 @@ URL = "https://insiderfoodie.com"
URL_SHORTENED_LENGTH = 23 # Twitter's shortened URL length URL_SHORTENED_LENGTH = 23 # Twitter's shortened URL length
CURRENT_YEAR = "2025" # Explicitly set the current year for the prompt CURRENT_YEAR = "2025" # Explicitly set the current year for the prompt
def setup_logging(): # Setup logging at the very start
"""Initialize logging with pruning of old logs.""" logger = logging.getLogger()
try: logger.setLevel(logging.DEBUG)
# Ensure the logs directory exists
os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
# Configure logging first # Clear any existing handlers (in case another script configured the logger)
logging.basicConfig( logger.handlers = []
filename=LOG_FILE,
level=logging.DEBUG, # Console handler
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
console_handler = logging.StreamHandler() console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')) console_handler.setLevel(logging.DEBUG)
console_handler.setLevel(logging.DEBUG) # Show DEBUG messages in console too console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S'))
logging.getLogger().addHandler(console_handler) logger.addHandler(console_handler)
logging.getLogger("openai").setLevel(logging.WARNING)
logging.getLogger("tweepy").setLevel(logging.WARNING)
# Now that logging is configured, prune old logs if the file exists # File handler
try:
os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
file_handler = logging.FileHandler(LOG_FILE, mode='a')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S'))
logger.addHandler(file_handler)
logging.info("File logging initialized successfully.")
except Exception as e:
logging.error(f"Failed to setup file logging to {LOG_FILE}: {e}. Continuing with console-only logging.")
# Prune old logs if the file exists
try:
if os.path.exists(LOG_FILE): if os.path.exists(LOG_FILE):
with open(LOG_FILE, 'r') as f: with open(LOG_FILE, 'r') as f:
lines = f.readlines() lines = f.readlines()
@ -73,22 +79,12 @@ def setup_logging():
logging.info(f"Skipped {malformed_count} malformed log lines during pruning") logging.info(f"Skipped {malformed_count} malformed log lines during pruning")
with open(LOG_FILE, 'w') as f: with open(LOG_FILE, 'w') as f:
f.writelines(pruned_lines) f.writelines(pruned_lines)
except Exception as e:
logging.warning(f"Failed to prune log file {LOG_FILE}: {e}")
logging.info("Logging initialized for foodie_engagement_tweet.py") logging.info("Logging initialized for foodie_engagement_tweet.py")
except Exception as e:
# Fallback to console-only logging if file logging fails
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
console_handler.setLevel(logging.DEBUG)
logging.getLogger().addHandler(console_handler)
logging.getLogger("openai").setLevel(logging.WARNING) logging.getLogger("openai").setLevel(logging.WARNING)
logging.getLogger("tweepy").setLevel(logging.WARNING) logging.getLogger("tweepy").setLevel(logging.WARNING)
logging.error(f"Failed to setup file logging to {LOG_FILE}: {e}. Falling back to console-only logging.")
def acquire_lock(): def acquire_lock():
"""Acquire a lock to prevent concurrent runs.""" """Acquire a lock to prevent concurrent runs."""
@ -434,7 +430,6 @@ def main():
lock_fd = None lock_fd = None
try: try:
lock_fd = acquire_lock() lock_fd = acquire_lock()
setup_logging()
post_engagement_tweet() post_engagement_tweet()
except Exception as e: except Exception as e:
logging.error(f"Fatal error in main: {e}", exc_info=True) logging.error(f"Fatal error in main: {e}", exc_info=True)

Loading…
Cancel
Save