Conceptualizing the Solution
\n\n
I'm focused on the core problem: building a Python script to verify website uptime and response times. Currently, I'm breaking down the overarching goal into smaller tasks, starting with understanding the essential functionalities. I'm considering using libraries like requests to handle the HTTP requests. Next, I need to figure out how to interpret the responses to determine uptime and measure response times precisely.
Mapping Out Implementation Steps
\n\n
My current thinking is focused on structuring the script. I'm moving beyond the initial concept and formulating the core logic. Specifically, I’m planning the import statements for requests and time. Also, I'm thinking about exception handling for potential issues like connection timeouts. I will likely use a try-except block to manage this.
Decomposing the Requirements
\n\n
My current thinking is focused on further breakdown. The core logic is clear, but I'm now outlining the structure of the script in more detail. I'm focusing on defining functions for checking a single URL, and then another one to loop through all URLs provided. Also, I'm considering error handling, specifically using try-except blocks to manage various network exceptions gracefully. Finally, I'm figuring out how to integrate logging, possibly including timestamps for each check.
Refining the Error Handling
\n\n
My current thinking centers on improving the script's robustness. I'm focusing on exception handling, specifically refining how I catch and interpret various requests exceptions. I'm considering logging detailed error messages to help pinpoint issues, such as connection timeouts or DNS resolution failures. Furthermore, I'm thinking about implementing retry mechanisms for transient errors.
Formulating the Implementation Plan
\n\n
My current thinking centers on the script's structure. I'm moving beyond individual function definitions and working on the overall flow. Specifically, I'm integrating continuous monitoring using a while loop, incorporating configurable intervals. Also, I am planning to add color-coded output to easily distinguish between "up" and "down" statuses in the console. Next, I am evaluating the use of a configuration file for the URLs and monitoring parameters.
Here are two versions of the script:
- Simple Version: A straightforward script to run a one-time check on a list of URLs.
- Advanced Version: A robust monitor that runs continuously, logs data to a CSV file, handles errors gracefully, and uses color-coded terminal output.
Prerequisites
You will need the requests library. If you don't have it, install it via terminal/command prompt:
pip install requests
1. Simple Version (One-time check)
This script checks a list of websites once and prints the results.
import requests
import time
def check_status(url):
try:
# Measure start time
start_time = time.time()
# Send request (timeout after 5 seconds)
response = requests.get(url, timeout=5)
# Measure end time
end_time = time.time()
# Calculate response time in milliseconds
response_time = (end_time - start_time) * 1000
if response.status_code == 200:
print(f"[UP] {url} - {response.status_code} - {response_time:.0f}ms")
else:
print(f"[WARN] {url} - Returned Status: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"[DOWN] {url} - Error: {e}")
if __name__ == "__main__":
websites = [
"https://www.google.com",
"https://www.github.com",
"https://www.nonexistent-website-example.com"
]
print("Checking websites...")
for site in websites:
check_status(site)
2. Advanced Version (Continuous Monitor & Logger)
This version includes:
- Continuous Loop: Checks every X seconds.
- CSV Logging: Saves history to
uptime_log.csv.
- Status Colors: Green for UP, Red for DOWN.
- Headers: Uses a User-Agent to avoid being blocked by bot filters.
import requests
import time
import csv
import os
from datetime import datetime
# --- CONFIGURATION ---
WEBSITES = [
"https://www.google.com",
"https://www.github.com",
"https://www.python.org",
"http://httpstat.us/500", # Test for server error
"http://httpstat.us/200?sleep=1000" # Test for latency
]
CHECK_INTERVAL = 10 # Seconds between checks
LOG_FILE = "uptime_log.csv"
TIMEOUT = 5 # Seconds before giving up connection
# --- COLORS FOR CONSOLE ---
class Colors:
GREEN = '\033[92m'
RED = '\033[91m'
YELLOW = '\033[93m'
RESET = '\033[0m'
def log_result(url, status, code, response_time, error_msg=""):
"""Appends the result to a CSV file."""
file_exists = os.path.isfile(LOG_FILE)
with open(LOG_FILE, 'a', newline='') as f:
writer = csv.writer(f)
# Write header if new file
if not file_exists:
writer.writerow(["Timestamp", "URL", "Status", "StatusCode", "ResponseTime_ms", "Error"])
writer.writerow([
datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
url,
status,
code,
f"{response_time:.2f}" if response_time else "",
error_msg
])
def check_website(url):
"""Checks a single website."""
headers = {'User-Agent': 'Python Uptime Monitor'}
try:
start_time = time.time()
response = requests.get(url, headers=headers, timeout=TIMEOUT)
end_time = time.time()
response_time = (end_time - start_time) * 1000 # Convert to ms
if response.status_code == 200:
print(f"{Colors.GREEN}[UP]{Colors.RESET} {url} | {response_time:.0f}ms")
log_result(url, "UP", response.status_code, response_time)
else:
print(f"{Colors.YELLOW}[WARN]{Colors.RESET} {url} | Status: {response.status_code}")
log_result(url, "WARN", response.status_code, response_time)
except requests.exceptions.Timeout:
print(f"{Colors.RED}[DOWN]{Colors.RESET} {url} | Connection Timed Out")
log_result(url, "DOWN", "", None, "Timeout")
except requests.exceptions.ConnectionError:
print(f"{Colors.RED}[DOWN]{Colors.RESET} {url} | Connection Error")
log_result(url, "DOWN", "", None, "Connection Error")
except requests.exceptions.RequestException as e:
print(f"{Colors.RED}[DOWN]{Colors.RESET} {url} | Error: {e}")
log_result(url, "DOWN", "", None, str(e))
def main():
print(f"Starting Monitor. Press Ctrl+C to stop.")
print(f"Logging to: {LOG_FILE}\n")
try:
while True:
print("-" * 40)
print(f"Check at {datetime.now().strftime('%H:%M:%S')}")
for site in WEBSITES:
check_website(site)
time.sleep(CHECK_INTERVAL)
except KeyboardInterrupt:
print("\nMonitor Stopped.")
if __name__ == "__main__":
main()
How it Works
requests.get(url): Sends an HTTP GET request to the server.
timeout=5: Crucial for monitoring. If the server doesn't respond in 5 seconds, the script stops waiting and marks it as a timeout/down rather than hanging indefinitely.
- Timing: We capture
time.time() before and after the request. Subtracting the two gives the duration in seconds. We multiply by 1000 to get milliseconds (ms), which is the standard unit for web latency.
- Status Codes:
- 200: Everything is normal.
- 4xx (e.g., 404): Client error (page not found). The site is "reachable", but the specific page is missing.
- 5xx (e.g., 500): Server error. The site is broken.
- Exceptions: We catch
requests.exceptions.ConnectionError (DNS failure, refused connection) and Timeout separately to give specific feedback.