Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions day-01/system_health.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#pyscipt to Check CPU Usages

import psutil

def check_cpu_usages(name,usages,limit):
if usages > limit:
print("CPU alert email Send High Use...")
else:
print("Usages is Ok")

for i in range(5):
cpu_limit = int(input("Enter CPU Threshold"))
memory_limit = int(input("Enter Memory Threshold"))
disk_limit = int(input("Enter Disk Threshhold"))
break
print("\n Checking Systems Usages...")

cpu_usage = psutil.cpu_percent(1)
memory_usage = psutil.virtual_memory().percent
disk_usage = psutil.disk_usage('/').percent

check_cpu_usages("CPU", cpu_usage, cpu_limit)

check_cpu_usages("Memory", memory_usage, memory_limit)

check_cpu_usages("Disk", disk_usage, disk_limit)
56 changes: 56 additions & 0 deletions day-02/api_data_fetcher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import requests
import json

BASE_URL = "https://pokeapi.co/api/v2/pokemon/"

def get_Pokemon(pokemon_name):
url = BASE_URL + pokemon_name.lower()
headers = {
"Accept": "application/json"
}

try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
data = response.json()

print("API is working... \n")

selected_data = {
"name": data["name"],
"id": data["id"],
"height": data["height"],
"weight": data["weight"],
}
print(json.dumps(selected_data, indent=4))

with open("output.json", "w", encoding="utf-8") as f:
json.dump(selected_data, f, indent=4)

print("Saving data to output.json ")

return selected_data

except requests.exceptions.RequestException as e:
print("API request failed ❌")
print("Error:", e)


except requests.exceptions.HTTPError:
print(f"❌ Pokémon '{pokemon_name}' not found!")

except ValueError:
print("Invalid JSON response ❌")


# pokemon_data = get_Pokemon()
def main():
pokemon_name = input("Enter Pokemon Name...Eg.Pikachu,ditto").strip()
# print("Eg.Pikachu,ditto")

if not pokemon_name:
print("Pokemon cannot be empty")

get_Pokemon(pokemon_name)

main()
6 changes: 6 additions & 0 deletions day-02/output.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "ditto",
"id": 132,
"height": 3,
"weight": 40
}
81 changes: 81 additions & 0 deletions day-03/system_health.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#pyscipt to Check CPU Usages Updated with Listed Changes
import psutil
from typing import Optional


def get_threshold(prompt: str) -> Optional[int]:
try:
value = int(input(prompt))
if not 0 <= value <= 100:
raise ValueError("Threshold must be between 0 and 100.")
return value
except ValueError as error:
print(f"[INPUT ERROR] {error}")
return None


def check_resource_usage(resource_name: str, usage: float, limit: int) -> None:
try:
if usage > limit:
print(
f"[ALERT] {resource_name} usage HIGH: "
f"{usage}% (limit: {limit}%)"
)
else:
print(f"[OK] {resource_name} usage normal: {usage}%")
except Exception as error:
print(f"[ERROR] Unable to check {resource_name}: {error}")


def get_system_usage() -> dict:
try:
return {
"CPU": psutil.cpu_percent(interval=1),
"Memory": psutil.virtual_memory().percent,
"Disk": psutil.disk_usage("/").percent,
}
except Exception as error:
print(f"[SYSTEM ERROR] Failed to fetch system usage: {error}")
return {}


def run_monitoring() -> None:
cpu_limit = get_threshold("Enter CPU threshold : ")
memory_limit = get_threshold("Enter Memory threshold : ")
disk_limit = get_threshold("Enter Disk threshold : ")

if None in (cpu_limit, memory_limit, disk_limit):
print("Invalid input detected. Returning to menu.\n")
return

print("\nChecking system usage...\n")

usage_data = get_system_usage()
if not usage_data:
print("No system data available. Returning to menu.\n")
return

check_resource_usage("CPU", usage_data["CPU"], cpu_limit)
check_resource_usage("Memory", usage_data["Memory"], memory_limit)
check_resource_usage("Disk", usage_data["Disk"], disk_limit)
print()


def main() -> None:
while True:
print("1. Enter thresholds")
print("2. Exit")

choice = input("Select an option (1 or 2): ").strip()

if choice == "1":
run_monitoring()
elif choice == "2":
print("Exiting program")
break
else:
print("[ERROR] Invalid choice. Please select 1 or 2.\n")


if __name__ == "__main__":
main()
30 changes: 15 additions & 15 deletions day-04/app.log
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
2025-01-10 09:00:01 INFO Application started successfully
2025-01-10 09:00:05 INFO Connecting to database
2025-01-10 09:00:07 INFO Database connection established
2026-01-26 10:00:01 INFO Application started successfully
2026-01-26 10:01:15 INFO Connecting to database
2026-01-26 10:02:30 INFO Database connection established

2025-01-10 09:05:12 WARNING High memory usage detected
2025-01-10 09:05:15 INFO Memory usage back to normal
2026-01-26 10:03:12 WARNING High memory usage detected
2026-01-10 09:05:15 INFO Memory usage back to normal

2025-01-10 09:10:22 ERROR Failed to fetch user data
2025-01-10 09:10:25 ERROR Database timeout occurred
2026-01-26 10:04:05 ERROR Failed to fetch user data
2026-01-26 10:05:20 ERROR Database timeout occurred

2025-01-10 09:15:30 INFO Retrying database connection
2025-01-10 09:15:32 INFO Database connection successful
2026-01-26 10:06:05 INFO Retrying database connection
2026-01-26 10:07:20 INFO Database connection successful

2025-01-10 09:20:45 WARNING Disk usage above 75%
2025-01-10 09:20:50 INFO Disk cleanup initiated
2026-01-26 10:08:05 WARNING Disk usage above 75%
2026-01-26 10:09:20 INFO Disk cleanup initiated

2025-01-10 09:25:10 ERROR Unable to write logs to disk
2025-01-10 09:25:15 INFO Log rotation completed
2026-01-26 10:10:05 ERROR Unable to write logs to disk
2026-01-26 10:11:20 INFO Log rotation completed

2025-01-10 09:30:00 INFO Application shutdown initiated
2025-01-10 09:30:05 INFO Application stopped
2026-01-26 10:12:05 INFO Application shutdown initiated
2026-01-26 10:13:20 INFO Application stopped
86 changes: 86 additions & 0 deletions day-04/log_analyzer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
#pyscipt to analyze logs using python
import json
from datetime import datetime
from typing import Dict, List


def read_log_file(file_path: str) -> List[str]:
try:
with open(file_path, "r") as f:
return f.readlines()
except FileNotFoundError:
print(f"[ERROR] File '{file_path}' not found.")
return []
except Exception as e:
print(f"[ERROR] Could not read file: {e}")
return []


def analyze_logs(lines: List[str]) -> Dict[str, int]:
"""Count INFO, WARNING, and ERROR messages."""
counts = {"INFO": 0, "WARNING": 0, "ERROR": 0}
for line in lines:
line = line.strip()
for level in counts:
if f" {level} " in line:
counts[level] += 1
break
return counts


def save_summary_txt(counts: Dict[str, int], file_path: str) -> None:
"""Save log summary to a TXT file."""
try:
with open(file_path, "w") as f:
f.write("=== Log Summary ===\n")
for level, count in counts.items():
f.write(f"{level}: {count}\n")
f.write("==================\n")
print(f"[INFO] Summary saved to '{file_path}'")
except Exception as e:
print(f"[ERROR] Could not write TXT summary: {e}")



def display_summary(counts: Dict[str, int], lines: List[str], show_errors: int = 5) -> None:
print("\n=== Log Summary ===")
for level, count in counts.items():
print(f"{level}: {count}")
error_lines = [line for line in lines if " ERROR " in line]
if error_lines:
print(f"\nFirst {min(show_errors, len(error_lines))} ERROR messages:")
for line in error_lines[:show_errors]:
print(f"- {line.strip()}")
print("==================\n")


def main() -> None:
while True:
print("1. Analyze log file")
print("2. Exit")
choice = input("Select an option (1 or 2): ").strip()

if choice == "1":
file_path = input("Enter path to log file: ").strip()
lines = read_log_file(file_path)
if not lines:
continue
counts = analyze_logs(lines)
display_summary(counts, lines)

# Save output files with timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
txt_file = f"log_summary_{timestamp}.txt"
json_file = f"log_summary_{timestamp}.json"
save_summary_txt(counts, txt_file)
# save_summary_json(counts, json_file)

elif choice == "2":
print("Exiting log analysis program.")
break
else:
print("[ERROR] Invalid choice. Please select 1 or 2.\n")


if __name__ == "__main__":
main()
5 changes: 5 additions & 0 deletions day-04/log_summary_20260126_150959.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
=== Log Summary ===
INFO: 10
WARNING: 2
ERROR: 3
==================
30 changes: 15 additions & 15 deletions day-05/app.log
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
2025-01-10 09:00:01 INFO Application started successfully
2025-01-10 09:00:05 INFO Connecting to database
2025-01-10 09:00:07 INFO Database connection established
2026-01-26 10:00:01 INFO Application started successfully
2026-01-26 10:01:15 INFO Connecting to database
2026-01-26 10:02:30 INFO Database connection established

2025-01-10 09:05:12 WARNING High memory usage detected
2025-01-10 09:05:15 INFO Memory usage back to normal
2026-01-26 10:03:12 WARNING High memory usage detected
2026-01-10 09:05:15 INFO Memory usage back to normal

2025-01-10 09:10:22 ERROR Failed to fetch user data
2025-01-10 09:10:25 ERROR Database timeout occurred
2026-01-26 10:04:05 ERROR Failed to fetch user data
2026-01-26 10:05:20 ERROR Database timeout occurred

2025-01-10 09:15:30 INFO Retrying database connection
2025-01-10 09:15:32 INFO Database connection successful
2026-01-26 10:06:05 INFO Retrying database connection
2026-01-26 10:07:20 INFO Database connection successful

2025-01-10 09:20:45 WARNING Disk usage above 75%
2025-01-10 09:20:50 INFO Disk cleanup initiated
2026-01-26 10:08:05 WARNING Disk usage above 75%
2026-01-26 10:09:20 INFO Disk cleanup initiated

2025-01-10 09:25:10 ERROR Unable to write logs to disk
2025-01-10 09:25:15 INFO Log rotation completed
2026-01-26 10:10:05 ERROR Unable to write logs to disk
2026-01-26 10:11:20 INFO Log rotation completed

2025-01-10 09:30:00 INFO Application shutdown initiated
2025-01-10 09:30:05 INFO Application stopped
2026-01-26 10:12:05 INFO Application shutdown initiated
2026-01-26 10:13:20 INFO Application stopped
Loading