3 min read

WordPress Uptime & Response Time Monitor

This utility monitors the uptime and response time of a WordPress website (or any website). It logs the status code and response time to a CSV file for historical tracking and prints alerts to the console if the site is down or slow.

Modules Used:

  • requests: To send HTTP requests and measure response time.
  • time: To handle scheduling and timestamps.
  • csv: To log data for analysis.
  • argparse: To handle command-line arguments.

The Code

Save this as uptime_monitor.py.

import requests
import time
import csv
import argparse
import os
from datetime import datetime

def log_status(file_path, timestamp, url, status_code, response_time, status):
    file_exists = os.path.isfile(file_path)

    with open(file_path, 'a', newline='') as f:
        writer = csv.writer(f)
        # Write header if file is new
        if not file_exists:
            writer.writerow(['Timestamp', 'URL', 'Status Code', 'Response Time (s)', 'Status'])

        writer.writerow([timestamp, url, status_code, f"{response_time:.4f}", status])

def check_site(url, threshold, log_file):
    try:
        start_time = time.time()
        # Set a timeout to prevent hanging indefinitely
        response = requests.get(url, timeout=10)
        end_time = time.time()

        response_time = end_time - start_time
        status_code = response.status_code

        if status_code == 200:
            if response_time > threshold:
                status = "SLOW"
                print(f"[WARNING] {url} is SLOW. Response: {response_time:.4f}s")
            else:
                status = "UP"
                print(f"[OK] {url} is UP. Response: {response_time:.4f}s")
        else:
            status = "DOWN"
            print(f"[ALERT] {url} returned status {status_code}")

    except requests.exceptions.Timeout:
        status_code = 0
        response_time = 10.0
        status = "TIMEOUT"
        print(f"[ALERT] {url} timed out.")
    except requests.exceptions.ConnectionError:
        status_code = 0
        response_time = 0.0
        status = "CONNECTION ERROR"
        print(f"[ALERT] Could not connect to {url}")
    except Exception as e:
        status_code = 0
        response_time = 0.0
        status = "ERROR"
        print(f"[ERROR] {e}")

    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_status(log_file, timestamp, url, status_code, response_time, status)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="WordPress Uptime Monitor")
    parser.add_argument("url", help="URL of the WordPress site")
    parser.add_argument("--interval", type=int, default=60, help="Check interval in seconds (default: 60)")
    parser.add_argument("--threshold", type=float, default=2.0, help="Slow response threshold in seconds (default: 2.0)")
    parser.add_argument("--log", default="uptime_log.csv", help="Log file path (default: uptime_log.csv)")

    args = parser.parse_args()

    print(f"Monitoring {args.url} every {args.interval} seconds...")
    print("Press Ctrl+C to stop.")

    try:
        while True:
            check_site(args.url, args.threshold, args.log)
            time.sleep(args.interval)
    except KeyboardInterrupt:
        print("\nMonitoring stopped.")

Usage

# Monitor a site every 30 seconds, flagging responses slower than 1.5s
python uptime_monitor.py https://my-wordpress-site.com --interval 30 --threshold 1.5

programming/python/python