Best Practices for Monitoring Systems in Flask Applications

Best Practices for Monitoring Systems in Flask Applications

Here is a Python script using Flask to create a simple web app that tracks system performance, such as CPU, memory, disk, and network activity. The data is shown in a web browser.

System Monitoring Web App with Flask

First, make sure you have Flask and psutil installed:

pip install flask psutil

Flask Application:

from flask import Flask, render_template
import psutil

app = Flask(__name__)

def get_cpu_usage():
    return psutil.cpu_percent(interval=1)

def get_memory_usage():
    mem = psutil.virtual_memory()
    return mem.percent

def get_disk_usage():
    disk = psutil.disk_usage('/')
    return disk.percent

def get_network_stats():
    net_io = psutil.net_io_counters()
    return net_io.bytes_sent, net_io.bytes_recv

@app.route('/')
def index():
    cpu_usage = get_cpu_usage()
    memory_usage = get_memory_usage()
    disk_usage = get_disk_usage()
    bytes_sent, bytes_recv = get_network_stats()

    return render_template('index.html', 
                           cpu_usage=cpu_usage, 
                           memory_usage=memory_usage, 
                           disk_usage=disk_usage, 
                           bytes_sent=bytes_sent / (1024 * 1024), 
                           bytes_recv=bytes_recv / (1024 * 1024))

if __name__ == "__main__":
    app.run(debug=True)

HTML Template:

Create a folder named templates in the same directory as your Flask script, and inside it, create a file named index.html. Here's a simple HTML template:

<!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>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        h1 {
            color: #333;
        }
        .stat {
            margin-bottom: 20px;
        }
        .stat span {
            font-weight: bold;
        }
    </style>
</head>
<body>
    <h1>System Monitoring Dashboard</h1>
    <div class="stat">
        <span>CPU Usage:</span> {{ cpu_usage }}%
    </div>
    <div class="stat">
        <span>Memory Usage:</span> {{ memory_usage }}%
    </div>
    <div class="stat">
        <span>Disk Usage:</span> {{ disk_usage }}%
    </div>
    <div class="stat">
        <span>Network Sent:</span> {{ bytes_sent }} MB
    </div>
    <div class="stat">
        <span>Network Received:</span> {{ bytes_recv }} MB
    </div>
</body>
</html>

Explanation:

  • Flask Routes: The / route renders the system statistics on the home page.

  • System Monitoring Functions: These functions use psutil to retrieve real-time data for CPU usage, memory usage, disk usage, and network statistics.

  • Rendering Data: The Flask render_template function is used to pass the system data to the HTML template.

  • HTML Template: The index.html template displays the system statistics in a simple web page format.

Running the Application:

  1. Save the Flask script (e.g., app.py) and the HTML template in the appropriate directory structure.

  2. Run the Flask application from the command line:

     python app.py
    
  3. Open your web browser and navigate to http://127.0.0.1:5000/ to view the system monitoring dashboard.

Output:

When you visit the web page, you’ll see something like this:

System Monitoring Dashboard
----------------------------
CPU Usage: 12.5%
Memory Usage: 57.2%
Disk Usage: 45.1%
Network Sent: 23.45 MB
Network Received: 45.89 MB

Conclusion:

This simple Flask app continuously monitors and shows real-time system stats. You can refresh the page to see updated info. You can also expand this app to include more metrics, charts, or even save the data for historical analysis.

Did you find this article valuable?

Support LingarajTechhub by becoming a sponsor. Any amount is appreciated!