How to Implement an Effective System: Get Alerts for Maximum Conditions
To send you a message when a system reaches its limit, we can update the Flask app to check for these conditions and send alerts. I'll add a simple way to log a message when certain limits are passed.
Modified Flask Application with Notifications:
from flask import Flask, render_template, jsonify
import psutil
app = Flask(__name__)
# Thresholds for maximum conditions
CPU_THRESHOLD = 90.0 # in percentage
MEMORY_THRESHOLD = 90.0 # in percentage
DISK_THRESHOLD = 90.0 # in percentage
NETWORK_THRESHOLD = 100.0 # in MB, for demonstration
def get_system_stats():
stats = {
"cpu_usage": psutil.cpu_percent(interval=1),
"memory_usage": psutil.virtual_memory().percent,
"disk_usage": psutil.disk_usage('/').percent,
"bytes_sent": psutil.net_io_counters().bytes_sent / (1024 * 1024), # MB
"bytes_recv": psutil.net_io_counters().bytes_recv / (1024 * 1024) # MB
}
return stats
def check_thresholds(stats):
messages = []
if stats['cpu_usage'] > CPU_THRESHOLD:
messages.append(f"CPU usage is high: {stats['cpu_usage']}%")
if stats['memory_usage'] > MEMORY_THRESHOLD:
messages.append(f"Memory usage is high: {stats['memory_usage']}%")
if stats['disk_usage'] > DISK_THRESHOLD:
messages.append(f"Disk usage is high: {stats['disk_usage']}%")
if stats['bytes_sent'] > NETWORK_THRESHOLD:
messages.append(f"Network sent is high: {stats['bytes_sent']:.2f} MB")
if stats['bytes_recv'] > NETWORK_THRESHOLD:
messages.append(f"Network received is high: {stats['bytes_recv']:.2f} MB")
return messages
@app.route('/')
def index():
return render_template('index.html')
@app.route('/system_stats')
def system_stats():
stats = get_system_stats()
notifications = check_thresholds(stats)
return jsonify(stats=stats, notifications=notifications)
if __name__ == "__main__":
app.run(debug=True)
Modifications in the HTML Template:
To display these notifications on the web interface, you can modify the index.html
template as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>System Monitoring Dashboard</title>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1 {
color: #333;
}
.chart {
width: 100%;
height: 400px;
margin-bottom: 40px;
}
#notifications {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<h1>System Monitoring Dashboard</h1>
<div id="cpuChart" class="chart"></div>
<div id="memoryChart" class="chart"></div>
<div id="diskChart" class="chart"></div>
<div id="networkChart" class="chart"></div>
<div id="notifications"></div>
<script>
var cpuData = [{
y: [0],
type: 'line',
name: 'CPU Usage (%)'
}];
var memoryData = [{
y: [0],
type: 'line',
name: 'Memory Usage (%)'
}];
var diskData = [{
y: [0],
type: 'line',
name: 'Disk Usage (%)'
}];
var networkData = [{
y: [0],
type: 'line',
name: 'Network Sent (MB)'
}, {
y: [0],
type: 'line',
name: 'Network Received (MB)'
}];
Plotly.newPlot('cpuChart', cpuData, {title: 'CPU Usage'});
Plotly.newPlot('memoryChart', memoryData, {title: 'Memory Usage'});
Plotly.newPlot('diskChart', diskData, {title: 'Disk Usage'});
Plotly.newPlot('networkChart', networkData, {title: 'Network Activity'});
function updateCharts() {
fetch('/system_stats')
.then(response => response.json())
.then(data => {
var time = new Date().toLocaleTimeString();
Plotly.extendTraces('cpuChart', { y: [[data.stats.cpu_usage]] }, [0]);
Plotly.extendTraces('memoryChart', { y: [[data.stats.memory_usage]] }, [0]);
Plotly.extendTraces('diskChart', { y: [[data.stats.disk_usage]] }, [0]);
Plotly.extendTraces('networkChart', { y: [[data.stats.bytes_sent], [data.stats.bytes_recv]] }, [0, 1]);
if(cpuData[0].y.length > 20) {
Plotly.relayout('cpuChart', {
xaxis: {
range: [cpuData[0].y.length - 20, cpuData[0].y.length]
}
});
Plotly.relayout('memoryChart', {
xaxis: {
range: [memoryData[0].y.length - 20, memoryData[0].y.length]
}
});
Plotly.relayout('diskChart', {
xaxis: {
range: [diskData[0].y.length - 20, diskData[0].y.length]
}
});
Plotly.relayout('networkChart', {
xaxis: {
range: [networkData[0].y.length - 20, networkData[0].y.length]
}
});
}
// Update notifications
document.getElementById('notifications').innerHTML = '';
if (data.notifications.length > 0) {
data.notifications.forEach(function(message) {
document.getElementById('notifications').innerHTML += '<p>' + message + '</p>';
});
}
});
}
setInterval(updateCharts, 2000);
</script>
</body>
</html>
Explanation:
Thresholds: The Flask app sets limits for CPU, memory, disk, and network usage.
Notifications: If system metrics go over these limits, a notification message is created.
Displaying Notifications: The
index.html
template shows these notifications on the webpage in red text.Real-Time Monitoring: The notifications update in real-time along with the graphs.
Running the Application:
Run the Flask application:
python app.py
Open your browser and navigate to
http://127.0.0.1:5000/
.
Output:
Graphs: Interactive graphs display real-time system stats.
Notifications: If any system metrics go over the set thresholds, a red notification message shows up on the web page to alert you.
This setup offers visual monitoring and notifications for critical issues, helping with proactive system management.