-
What Grafana version and what operating system are you using?
v11.1.0 (5b85c4c2fc) -
What are you trying to achieve?
I would like to represent the server CPU utilization graph in real time through Time series graphs with Postgresql, python and Grafana.
- How are you trying to achieve it?
1.create table
CREATE TABLE cpu_usage (
id SERIAL PRIMARY KEY,
server_name TEXT NOT NULL,
timestamp TIMESTAMP NOT NULL,
cpu_usage_percentage DECIMAL(5, 2) NOT NULL
);
2.query CPU usage and load data into Postgresql.
import psutil
import psycopg2
from datetime import datetime
import time
# Database connection
conn = psycopg2.connect(
dbname="my_test_db",
user="my_username",
password="my_password",
host="my_host",
port="my_port"
)
cursor = conn.cursor()
# Function to insert CPU usage data
def log_cpu_usage(server_name):
cpu_usage = psutil.cpu_percent(interval=1) # Get CPU usage over 1 second
timestamp = datetime.now()
cursor.execute("""
INSERT INTO cpu_usage (server_name, timestamp, cpu_usage_percentage)
VALUES (%s, %s, %s)
""", (server_name, timestamp, cpu_usage))
conn.commit()
# Run the logging in an infinite loop every 10 seconds
try:
while True:
log_cpu_usage('my_server')
time.sleep(9) # Sleeps for 9 seconds, making the total time 10 seconds with psutil.cpu_percent's 1-second interval
except KeyboardInterrupt:
print("Stopping CPU usage logging.")
# Close the connection
cursor.close()
conn.close()
Use Grafana to represent it
- What happened?
Grafana doesnât draw a utilization curve, it only shows the message âData outside time rangeâ, and when I click the Zoom to data button, it shows me the graph I want, as shown below:
For this method of displaying the graphs by clicking the Zoom to data button, when I click the âsaveâ and âapplyâ buttons and set the panel auto-refresh time to 5 seconds, the graphs donât refresh in real time as I expected, but I need to click the Zoom to data button again for the graphs to refresh.
- What did you expect to happen?
I was expecting Grafana to refresh the graphs in real time, as I expected, instead of reporting âData outside time rangeâ.
- Can you copy/paste the configuration(s) that you are having problems with?
Yesďź This is my configuration:
my sql script:
SELECT
timestamp AS "time",
cpu_usage_percentage AS "CPU Usage (%)"
FROM
cpu_usage
WHERE
server_name = 'my_server'
ORDER BY
timestamp
Postgresql tables manipulated by this script
- Did you receive any errors in the Grafana UI or in related logs? If so, please tell us exactly what they were.
I only got this message: Data outside time range
- Did you follow any online instructions? If so, what is the URL?