AW Dev Rethought

Code is read far more often than it is written - Guido van Rossum

🧩 Python Automation Recipes – 🌐 Website Uptime Monitor


Description:

📌 Introduction

Websites don’t always fail loudly. Sometimes they go down quietly — and you only find out later.

A simple uptime monitor helps you detect outages early and keep a log of when things go wrong.

This automation recipe shows how to ping a website at regular intervals and log downtime events using Python.

It’s lightweight, easy to extend, and perfect for small services, side projects, or internal tools.


🔎 Explanation

  • The script sends periodic HTTP requests to a target URL using requests.
  • If the site responds with a successful status code, it’s considered UP.
  • If the request fails or times out, the event is logged as DOWN with a timestamp.
  • All downtime events are appended to a log file for later review.

This is a common pattern used in:

  • basic monitoring systems
  • cron-based health checks
  • lightweight DevOps scripts

✅ Key Takeaways

  • 🌐 Monitor website availability automatically.
  • ⏱️ Detect and log downtime with timestamps.
  • 📄 Simple logs you can audit or alert on later.

Code Snippet:

import requests
import time
from datetime import datetime
from pathlib import Path

# --- Step 1: Configuration ---

# Website to monitor
URL = "https://awdevrethought.com"  # change this to your desired website

# Time between checks (in seconds)
CHECK_INTERVAL = 60  # 1 minute

# Log file for downtime events
LOG_FILE = Path("uptime_log.txt")

# Request timeout (seconds)
TIMEOUT = 10

print(f"Monitoring uptime for: {URL}")
print(f"Check interval: {CHECK_INTERVAL} seconds\n")

# --- Step 2: Monitoring loop ---
while True:
    try:
        response = requests.get(URL, timeout=TIMEOUT)

        if response.status_code == 200:
            print(f"[{datetime.now()}] ✅ WEBSITE IS UP!")
        else:
            raise Exception(f"Status code: {response.status_code}")

    except Exception as e:
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        message = f"[{timestamp}] ❌ WEBSITE IS DOWN! – {e}"

        # Log downtime event
        with LOG_FILE.open("a") as f:
            f.write(message + "\n")

        print(message)

    time.sleep(CHECK_INTERVAL)

Link copied!

Comments

Add Your Comment

Comment Added!