Skip to content

Commit b021d11

Browse files
Refactor system info logging and metrics collection
- Refactor the `log_system_info` function to check if system info logging is enabled before scheduling the next log. - Add a new function `is_logging_enabled` to check if system info logging is enabled in the general settings. - Add a new function `schedule_next_log` to schedule the next logging event after a specified interval. - Update the `log_system_info_to_db` function to also update Prometheus metrics with the latest system information. - Add a new function `update_prometheus_metrics` to update Prometheus metrics with the latest system information. - Add a new function `store_system_info_in_db` to store the collected system information into the database. - Remove the unused `monitor_settings` function. Fix memory info route and template - Add the `dashboard_memory_usage` value to the `memory_info` dictionary in the `memory_usage` function. - Update the `memory_info.html` template to include the `dashboard_memory` card component. Remove unused code from Prometheus route - Remove the unused code for collecting system metrics and updating Prometheus gauges.
1 parent 1ca4650 commit b021d11

4 files changed

Lines changed: 92 additions & 98 deletions

File tree

src/background_task/log_system_info.py

Lines changed: 86 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -6,102 +6,142 @@
66
from src.logger import logger
77
from src.models import GeneralSettings, SystemInformation
88
from sqlalchemy.exc import SQLAlchemyError
9-
from src.logger import logger
9+
from prometheus_client import Counter, Gauge
1010

11-
# Flag to check if logging is already scheduled
11+
# Flag to track if logging is already scheduled
1212
is_logging_scheduled = False
1313

14+
# Initialize Prometheus metrics
15+
metrics = {
16+
'cpu_usage_metric': Gauge('cpu_usage_percentage', 'Current CPU usage percentage'),
17+
'memory_usage_metric': Gauge('memory_usage_percentage', 'Current memory usage percentage'),
18+
'disk_usage_metric': Gauge('disk_usage_percentage', 'Disk usage percentage'),
19+
'network_sent_metric': Gauge('network_bytes_sent', 'Total network bytes sent'),
20+
'network_recv_metric': Gauge('network_bytes_received', 'Total network bytes received'),
21+
'cpu_temp_metric': Gauge('cpu_temperature', 'Current CPU temperature'),
22+
'cpu_frequency_metric': Gauge('cpu_frequency', 'Current CPU frequency'),
23+
'battery_percentage_metric': Gauge('battery_percentage', 'Current battery percentage'),
24+
'dashboard_memory_usage_metric': Gauge('dashboard_memory_usage_percentage', 'Current memory usage percentage'),
25+
'request_count': Counter('http_requests_total', 'Total HTTP requests made')
26+
}
1427

1528
def log_system_info():
1629
"""
1730
Logs system information at regular intervals based on the general settings.
18-
This function checks if logging is still active before each logging event.
31+
This function checks if logging is enabled and schedules the next log if active.
1932
"""
2033
global is_logging_scheduled
2134
with app.app_context():
2235
try:
23-
# Fetch the general settings to check if logging is enabled
24-
general_settings = GeneralSettings.query.first()
25-
is_logging_system_info = (
26-
general_settings.is_logging_system_info if general_settings else False
27-
)
28-
29-
if not is_logging_system_info:
36+
if not is_logging_enabled():
3037
logger.info("System info logging has been stopped.")
31-
is_logging_scheduled = False # Reset the flag if logging stops
38+
is_logging_scheduled = False
3239
return
3340

3441
log_system_info_to_db()
3542
logger.debug("System information logged successfully.")
36-
37-
# Schedule the next log after 60 seconds
38-
Timer(60, log_system_info).start()
43+
schedule_next_log()
3944

4045
except Exception as e:
4146
logger.error(f"Error during system info logging: {e}", exc_info=True)
42-
is_logging_scheduled = False # Reset the flag in case of an error
47+
is_logging_scheduled = False
48+
49+
50+
def is_logging_enabled():
51+
"""
52+
Checks if system info logging is enabled in the general settings.
53+
"""
54+
try:
55+
general_settings = GeneralSettings.query.first()
56+
return general_settings.is_logging_system_info if general_settings else False
57+
except SQLAlchemyError as e:
58+
logger.error(f"Error fetching general settings: {e}", exc_info=True)
59+
return False
60+
61+
62+
def schedule_next_log(interval=60):
63+
"""
64+
Schedules the next logging event after the specified interval (in seconds).
65+
"""
66+
Timer(interval, log_system_info).start()
4367

4468

4569
def log_system_info_to_db():
4670
"""
47-
Fetches system information and logs it to the database.
71+
Fetches system information and logs it to the database and updates Prometheus metrics.
4872
"""
4973
with app.app_context():
5074
try:
5175
system_info = _get_system_info()
52-
system_log = SystemInformation(
53-
cpu_percent=system_info["cpu_percent"],
54-
memory_percent=system_info["memory_percent"],
55-
battery_percent=system_info["battery_percent"],
56-
network_sent=system_info["network_sent"],
57-
network_received=system_info["network_received"],
58-
dashboard_memory_usage=system_info["dashboard_memory_usage"],
59-
cpu_frequency=system_info["cpu_frequency"],
60-
current_temp=system_info["current_temp"],
61-
timestamp=datetime.datetime.now(),
62-
)
63-
db.session.add(system_log)
64-
db.session.commit()
76+
77+
# Update Prometheus metrics
78+
update_prometheus_metrics(system_info)
79+
80+
# Store system information in the database
81+
store_system_info_in_db(system_info)
6582
logger.info("System information logged to database.")
6683

6784
except SQLAlchemyError as db_err:
68-
logger.error(
69-
f"Database error while logging system info: {db_err}", exc_info=True
70-
)
85+
logger.error(f"Database error while logging system info: {db_err}", exc_info=True)
7186
db.session.rollback()
7287
except Exception as e:
7388
logger.error(f"Failed to log system information: {e}", exc_info=True)
7489

90+
91+
def update_prometheus_metrics(system_info):
92+
"""
93+
Updates Prometheus metrics with the latest system information.
94+
"""
95+
metrics['cpu_usage_metric'].set(system_info['cpu_percent'])
96+
metrics['memory_usage_metric'].set(system_info['memory_percent'])
97+
metrics['disk_usage_metric'].set(system_info['disk_percent'])
98+
metrics['network_sent_metric'].set(system_info['network_sent'])
99+
metrics['network_recv_metric'].set(system_info['network_received'])
100+
metrics['cpu_temp_metric'].set(system_info['current_temp'])
101+
metrics['cpu_frequency_metric'].set(system_info['cpu_frequency'])
102+
metrics['battery_percentage_metric'].set(system_info['battery_percent'])
103+
metrics['dashboard_memory_usage_metric'].set(system_info['dashboard_memory_usage'])
104+
metrics['request_count'].inc()
105+
106+
107+
def store_system_info_in_db(system_info):
108+
"""
109+
Stores the collected system information into the database.
110+
"""
111+
system_log = SystemInformation(
112+
cpu_percent=system_info["cpu_percent"],
113+
memory_percent=system_info["memory_percent"],
114+
battery_percent=system_info["battery_percent"],
115+
network_sent=system_info["network_sent"],
116+
network_received=system_info["network_received"],
117+
dashboard_memory_usage=system_info["dashboard_memory_usage"],
118+
cpu_frequency=system_info["cpu_frequency"],
119+
current_temp=system_info["current_temp"],
120+
timestamp=datetime.datetime.now(),
121+
)
122+
db.session.add(system_log)
123+
db.session.commit()
124+
125+
75126
def monitor_settings():
76127
"""
77128
Monitors application general settings for changes and controls system logging dynamically.
78-
This function runs periodically to check for updates to logging settings.
79129
"""
80130
global is_logging_scheduled
81131
with app.app_context():
82132
try:
83-
# Fetch the general settings
84-
general_settings = GeneralSettings.query.first()
85-
86-
# Check if logging should be active or not
87-
is_logging_system_info = (
88-
general_settings.is_logging_system_info if general_settings else False
89-
)
90-
if is_logging_system_info:
133+
if is_logging_enabled():
91134
logger.info("System logging enabled. Starting system info logging.")
92-
93-
# Schedule logging only if not already scheduled
94135
if not is_logging_scheduled:
95136
logger.debug("Scheduling system info logging.")
96137
Timer(0, log_system_info).start()
97138
is_logging_scheduled = True
98139
else:
99140
logger.info("System logging disabled. Stopping system info logging.")
100-
is_logging_scheduled = False # Reset the flag if logging is disabled
141+
is_logging_scheduled = False
101142

102-
# Check settings periodically (every 10 seconds)
143+
# Recheck settings every 10 seconds
103144
Timer(10, monitor_settings).start()
104145

105146
except SQLAlchemyError as db_err:
106147
logger.error(f"Error fetching settings: {db_err}", exc_info=True)
107-

src/routes/memory_info.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from flask_login import login_required
33

44
from src.config import app
5-
from src.utils import get_cached_value, get_memory_percent, get_memory_available, get_memory_used, get_swap_memory_info
5+
from src.utils import get_cached_value, get_memory_percent, get_memory_available, get_memory_used, get_swap_memory_info, get_flask_memory_usage
66
from src.routes.helper.common_helper import check_page_toggle
77

88
memory_info_bp = blueprints.Blueprint("memory_usage", __name__)
@@ -17,6 +17,7 @@ def memory_usage():
1717
"memory_percent": get_memory_percent(),
1818
"memory_available": memory_available,
1919
"memory_used": get_memory_used(),
20+
'dashboard_memory_usage': get_flask_memory_usage(),
2021
}
2122

2223
swap_info = get_swap_memory_info()

src/routes/prometheus.py

Lines changed: 1 addition & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,10 @@
11
from flask import Blueprint, Response
2-
from prometheus_client import Counter, Gauge, generate_latest
3-
import threading
4-
import time
2+
from prometheus_client import generate_latest
53
from src.config import app
6-
from src.utils import _get_system_info
74

85
# Define the Prometheus Blueprint
96
prometheus_bp = Blueprint('prometheus', __name__)
107

11-
# Initialize Prometheus metrics
12-
cpu_usage_metric = Gauge('cpu_usage_percentage', 'Current CPU usage percentage')
13-
memory_usage_metric = Gauge('memory_usage_percentage', 'Current memory usage percentage')
14-
disk_usage_metric = Gauge('disk_usage_percentage', 'Disk usage percentage')
15-
network_sent_metric = Gauge('network_bytes_sent', 'Total network bytes sent')
16-
network_recv_metric = Gauge('network_bytes_received', 'Total network bytes received')
17-
request_count = Counter('http_requests_total', 'Total HTTP requests made')
18-
cpu_temp_metric = Gauge('cpu_temperature', 'Current CPU temperature')
19-
cpu_frequency_metric = Gauge('cpu_frequency', 'Current CPU frequency')
20-
battery_percentage_metric = Gauge('battery_percentage', 'Current battery percentage')
21-
dashboard_memory_usage_metric = Gauge('dashboard_memory_usage_percentage', 'Current memory usage percentage')
22-
23-
24-
def collect_metrics():
25-
"""
26-
Collect system metrics and update Prometheus Gauges.
27-
Runs in a separate thread and updates metrics every 5 seconds.
28-
"""
29-
while True:
30-
try:
31-
# Gather system information
32-
system_info = _get_system_info()
33-
34-
# Update Prometheus metrics
35-
cpu_usage_metric.set(system_info['cpu_percent'])
36-
memory_usage_metric.set(system_info['memory_percent'])
37-
disk_usage_metric.set(system_info['disk_percent'])
38-
network_sent_metric.set(system_info['network_sent'])
39-
network_recv_metric.set(system_info['network_received'])
40-
cpu_temp_metric.set(system_info['current_temp'])
41-
cpu_frequency_metric.set(system_info['cpu_frequency'])
42-
battery_percentage_metric.set(system_info['battery_percent'])
43-
dashboard_memory_usage_metric.set(system_info['dashboard_memory_usage'])
44-
45-
46-
# Increment HTTP request counter
47-
request_count.inc()
48-
except Exception as e:
49-
print(f"Error collecting metrics: {e}")
50-
51-
# Sleep for 5 seconds before the next collection
52-
time.sleep(10)
53-
54-
# Start the metrics collection in a background thread
55-
metrics_thread = threading.Thread(target=collect_metrics, daemon=True)
56-
metrics_thread.start()
57-
588
# Define a route to serve Prometheus metrics
599
@app.route('/metrics')
6010
def metrics():

src/templates/info_pages/memory_info.html

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ <h2 class="my-4">Memory
1414
<div class="col-md-6 col-lg-4 mb-4">
1515
{% include 'card_comp/memory/used.html' %}
1616
</div>
17+
<div class="col-md-6 col-lg-4 mb-4">
18+
{% include 'card_comp/memory/dashboard_memory.html' %}
19+
</div>
1720
<div class="col-md-6 col-lg-4 mb-4">
1821
{% include 'card_comp/memory/swap_total.html' %}
1922
</div>

0 commit comments

Comments
 (0)