Skip to content

Commit 2a991ab

Browse files
committed
feat: add memory monitoring script and documentation
- Introduced a new Python script for monitoring system memory usage and alerting users when specific thresholds are exceeded. - Added a .gitignore file to exclude unnecessary files from version control. - Created a README file with documentation on usage, features, requirements, and configuration options.
0 parents  commit 2a991ab

File tree

3 files changed

+186
-0
lines changed

3 files changed

+186
-0
lines changed

.gitignore

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
6+
# Distribution / packaging
7+
dist/
8+
build/
9+
*.egg-info/
10+
11+
# PyInstaller
12+
*.manifest
13+
*.spec
14+
15+
# Logs
16+
*.log
17+
18+
# Virtual environments
19+
venv/
20+
.venv/
21+
env/
22+
ENV/
23+
24+
# OS specific files
25+
.DS_Store
26+
Thumbs.db
27+
28+
# Project specific
29+
*.bak

main.py

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
#!/usr/bin/env python3
2+
3+
import logging
4+
import time
5+
6+
import psutil
7+
8+
9+
def main():
10+
setup_logging()
11+
12+
# Track how long memory has been high
13+
high_memory_min_duration = 120
14+
high_memory_threshold = 80
15+
16+
print("Memory Monitor Started...")
17+
print("Monitoring for:")
18+
print(
19+
f" - Memory usage > {high_memory_threshold}% for {high_memory_min_duration // 60} minutes"
20+
)
21+
print(" - Swap memory usage")
22+
print(" - OOM kill events")
23+
24+
high_memory_start_time = None
25+
26+
while True:
27+
try:
28+
check_memory_usage(
29+
high_memory_start_time,
30+
duration=high_memory_min_duration,
31+
threshold=high_memory_threshold,
32+
)
33+
check_swap_usage()
34+
check_oom_kills()
35+
time.sleep(10) # Check every 10 seconds
36+
except KeyboardInterrupt:
37+
print("Memory monitoring stopped.")
38+
break
39+
except Exception as e:
40+
logging.error(f"Error during monitoring: {e}")
41+
42+
43+
def setup_logging():
44+
logging.basicConfig(
45+
level=logging.INFO,
46+
format="%(asctime)s - %(levelname)s - %(message)s",
47+
filename="memory_monitor.log",
48+
)
49+
50+
51+
def check_memory_usage(high_memory_start_time, **kwargs):
52+
mem = psutil.virtual_memory()
53+
mem_percent = mem.percent
54+
duration = kwargs.get("duration", 120)
55+
threshold = kwargs.get("threshold", 80)
56+
57+
if mem_percent > threshold:
58+
if high_memory_start_time is None:
59+
high_memory_start_time = time.time()
60+
logging.warning(f"Memory usage high: {mem_percent:.1f}%")
61+
else:
62+
duration = time.time() - high_memory_start_time
63+
if duration >= duration:
64+
logging.critical(
65+
f"HIGH MEMORY ALERT: {mem_percent:.1f}% for {duration:.0f} seconds"
66+
)
67+
else:
68+
if high_memory_start_time is not None:
69+
logging.info(f"Memory usage returned to normal: {mem_percent:.1f}%")
70+
high_memory_start_time = None
71+
72+
return high_memory_start_time
73+
74+
75+
def check_swap_usage():
76+
swap = psutil.swap_memory()
77+
if swap.used > 0:
78+
swap_percent = swap.percent
79+
logging.warning(
80+
f"Swap memory in use: {swap.used / (1024**3):.2f} GB ({swap_percent:.1f}%)"
81+
)
82+
print(
83+
f"ALERT: Swap memory in use: {swap.used / (1024**3):.2f} GB ({swap_percent:.1f}%)"
84+
)
85+
86+
87+
def check_oom_kills():
88+
try:
89+
with open("/proc/vmstat", "r") as f:
90+
for line in f:
91+
if "oom_kill" in line:
92+
parts = line.strip().split()
93+
if len(parts) >= 2 and int(parts[1]) > 0:
94+
logging.critical(f"OOM kill detected: {parts[1]} occurrences")
95+
except Exception as e:
96+
logging.error(f"Error checking OOM kills: {e}")
97+
98+
99+
if __name__ == "__main__":
100+
main()

readme.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# Memory Monitor
2+
3+
A lightweight Python utility that monitors system memory usage and alerts when memory thresholds are exceeded.
4+
5+
## Features
6+
7+
- Monitors system memory usage in real-time
8+
- Alerts when memory usage exceeds configurable thresholds for extended periods
9+
- Detects and reports swap memory usage
10+
- Monitors for OOM (Out Of Memory) kill events
11+
- Logs all events to a log file for later analysis
12+
13+
## Requirements
14+
15+
- Python 3.6+
16+
- psutil library
17+
18+
## Installation
19+
20+
1. Clone this repository or download the script:
21+
22+
```bash
23+
git clone https://github.com/asrul10/simple-memory-monitor.git
24+
cd simple-memory-monitor
25+
```
26+
27+
2. Install the required dependencies:
28+
29+
```bash
30+
pip install psutil
31+
```
32+
33+
## Usage
34+
35+
Run the script with Python:
36+
37+
```bash
38+
python main.py
39+
```
40+
41+
The script will start monitoring your system memory and provide alerts when:
42+
- Memory usage exceeds 80% for 2 minutes or more
43+
- Any swap memory is being used
44+
- OOM kill events are detected
45+
46+
All alerts are displayed in the console and also logged to `memory_monitor.log`.
47+
48+
## Configuration
49+
50+
You can modify the following variables in the `main()` function to adjust monitoring thresholds:
51+
52+
- `high_memory_threshold`: Percentage of memory usage that triggers an alert (default: 80%)
53+
- `high_memory_min_duration`: Minimum duration in seconds that memory must remain high to trigger an alert (default: 120 seconds)
54+
55+
## Log File
56+
57+
The script creates a log file named `memory_monitor.log` in the same directory. This file contains all monitoring events with timestamps.

0 commit comments

Comments
 (0)