diff --git a/.env.example b/.env.example index c151833..ae2f6e6 100644 --- a/.env.example +++ b/.env.example @@ -10,6 +10,9 @@ SELECTOR_TYPE=xpath # Cache file location (stores the hash of previous content) CACHE_FILE=.cache/hash.txt +# Optional: Log file path (leave empty to only log to console) +LOG_FILE=.logs/alert.log + # SMTP Email Configuration SMTP_HOST=smtp.gmail.com SMTP_PORT=587 diff --git a/.gitignore b/.gitignore index a6edab3..0da362e 100644 --- a/.gitignore +++ b/.gitignore @@ -214,3 +214,4 @@ __marimo__/ # ---------------------------------- .env +.logs diff --git a/alert.py b/alert.py index 58fdff0..7b86b79 100644 --- a/alert.py +++ b/alert.py @@ -7,6 +7,7 @@ Supports optional XPath/CSS selectors for monitoring specific page sections. import hashlib import logging +import logging.handlers import smtplib import sys from email.mime.multipart import MIMEMultipart @@ -128,13 +129,40 @@ def send_email( def main() -> int: """Main execution function.""" - # Logging to INFO - logging.basicConfig(level=logging.INFO, format="[%(asctime)s] %(levelname)s: %(message)s") - # Load configuration from environment env = Env() env.read_env() + # Configure logging + log_format = "[%(asctime)s] %(levelname)s: %(message)s" + log_level = logging.INFO + + # Get log file path from environment (optional) + log_file = env.str("LOG_FILE", default=None) + + # Setup logging handlers + handlers = [] + + # Always add console handler + console_handler = logging.StreamHandler() + console_handler.setFormatter(logging.Formatter(log_format)) + handlers.append(console_handler) + + # Add file handler if log file is configured + if log_file: + log_path = Path(log_file) + log_path.parent.mkdir(parents=True, exist_ok=True) + file_handler = logging.handlers.RotatingFileHandler( + log_path, + maxBytes=10 * 1024 * 1024, # 10 MB + backupCount=5 + ) + file_handler.setFormatter(logging.Formatter(log_format)) + handlers.append(file_handler) + + # Configure root logger + logging.basicConfig(level=log_level, format=log_format, handlers=handlers, force=True) + url = env.str("URL") selector = env.str("SELECTOR", default=None) selector_type = env.str("SELECTOR_TYPE", default="xpath")