ZBLOG

Prometheus api node_systemd_unit_state查询监控数据导出Excel

要使用Prometheus API和Python将查询结果导出为Excel,需要安装以下模块:

  1. prometheus-api-client:用于连接和查询Prometheus API
  2. pandas:用于处理数据和生成Excel文件
  3. openpyxl:用于创建Excel工作簿

首先,使用prometheus-api-client模块连接到Prometheus服务器并执行查询:

from prometheus_api_client import PrometheusConnect

# Connect to Prometheus server
prom = PrometheusConnect(url='http://localhost:9090')

# Query node_systemd_unit_state metric
query = 'node_systemd_unit_state{state="active"}'
result = prom.custom_query(query)

然后,将查询结果转换为pandas DataFrame格式,并根据需要进行数据清理和转换:

import pandas as pd

# Convert result to pandas DataFrame
df = pd.DataFrame(result)

# Clean up data and rename columns
df.columns = ['labels', 'value', 'timestamp']
df['service'] = df['labels'].apply(lambda x: x['name'])
df['unit'] = df['labels'].apply(lambda x: x['unit'])
df.drop(columns=['labels'], inplace=True)

最后,使用openpyxl模块创建一个新的Excel工作簿,并将pandas DataFrame写入其中:

from openpyxl import Workbook

# Create a new Excel workbook and worksheet
wb = Workbook()
ws = wb.active

# Write the DataFrame to the worksheet
for r in dataframe_to_rows(df, index=False, header=True):
    ws.append(r)

# Save the workbook to a file
wb.save('output.xlsx')

完整代码示例:

from prometheus_api_client import PrometheusConnect
import pandas as pd
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows

# Connect to Prometheus server
prom = PrometheusConnect(url='http://localhost:9090')

# Query node_systemd_unit_state metric
query = 'node_systemd_unit_state{state="active"}'
result = prom.custom_query(query)

# Convert result to pandas DataFrame
df = pd.DataFrame(result)

# Clean up data and rename columns
df.columns = ['labels', 'value', 'timestamp']
df['service'] = df['labels'].apply(lambda x: x['name'])
df['unit'] = df['labels'].apply(lambda x: x['unit'])
df.drop(columns=['labels'], inplace=True)

# Create a new Excel workbook and worksheet
wb = Workbook()
ws = wb.active

# Write the DataFrame to the worksheet
for r in dataframe_to_rows(df, index=False, header=True):
    ws.append(r)

# Save the workbook to a file
wb.save('output.xlsx')

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=3740

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?