python

Python Promeheus

2020-06-19  本文已影响0人  wit92

普罗米修斯Python客户端

Prometheus的官方Python 2和3客户端。

一.三步演示

1 .安装客户端
pip install prometheus_client
2.将以下内容粘贴到Python解释器中
from prometheus_client import start_http_server, Summary
import random
import time

# Create a metric to track time spent and requests made.
REQUEST_TIME = Summary('request_processing_seconds', 'Time spent processing request')

# Decorate function with metric.
@REQUEST_TIME.time()
def process_request(t):
    """A dummy function that takes some time."""
    time.sleep(t)

if __name__ == '__main__':
    # Start up the server to expose the metrics.
    start_http_server(8000)
    # Generate some requests.
    while True:
        process_request(random.random())
3.访问http:// localhost:8000 /查看指标

从一个易于使用的装饰器得到:

Prometheus的rate功能允许计算每秒的两个请求
以及此数据随时间的延迟。

此外,如果您使用的是Linux,则process指标会
免费公开CPU,内存和有关该过程的其他信息!

安装
pip install prometheus_client

这个包可以在PyPI上找到

插装

提供四种类型的度量:计数器,仪表,摘要和直方图。
请参阅 有关如何使用它们的度量标准类型
和检测最佳实践的文档。

计数器

计数器上升,并在进程重新启动时重置。

from prometheus_client import Counter
c = Counter('my_failures_total', 'Description of counter')
c.inc()     # Increment by 1
c.inc(1.6)  # Increment by given value

有些实用程序可以计算引发的异常:

@c.count_exceptions()
def f():
  pass

with c.count_exceptions():
  pass

# Count only one type of exception
with c.count_exceptions(ValueError):
  pass

仪表可以上下移动。

from prometheus_client import Gauge
g = Gauge('my_inprogress_requests', 'Description of gauge')
g.inc()      # Increment by 1
g.dec(10)    # Decrement by given value
g.set(4.2)   # Set to a given value

有常见用例的实用程序:

g.set_to_current_time()   # Set to current unixtime

# Increment when entered, decrement when exited.
@g.track_inprogress()
def f():
  pass

with g.track_inprogress():
  pass

Gauge也可以从回调中获取其值:

d = Gauge('data_objects', 'Number of objects')
my_dict = {}
d.set_function(lambda: len(my_dict))
摘要

摘要跟踪事件的大小和数量。

from prometheus_client import Summary
s = Summary('request_latency_seconds', 'Description of summary')
s.observe(4.7)    # Observe 4.7 (seconds in this case)

有用于计时代码的实用程序:

@s.time()
def f():
  pass

with s.time():
  pass

Python客户端此时不存储或公开分位数信息。

直方图

直方图跟踪存储桶中事件的大小和数量。
这允许分位数的可聚合计算。

from prometheus_client import Histogram
h = Histogram('request_latency_seconds', 'Description of histogram')
h.observe(4.7)    # Observe 4.7 (seconds in this case)

默认存储桶旨在涵盖从毫秒到秒的典型Web / rpc请求。
可以通过传递buckets关键字参数来覆盖它们Histogram。

有用于计时代码的实用程序:

@h.time()
def f():
  pass

with h.time():
  pass
标签

所有指标都可以包含标签,允许对相关时间序列进行分组。

查看有关命名
和标签的最佳做法。

以柜台为例:

from prometheus_client import Counter
c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint'])
c.labels('get', '/').inc()
c.labels('post', '/submit').inc()

标签也可以作为关键字参数传递:

from prometheus_client import Counter
c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint'])
c.labels(method='get', endpoint='/').inc()
c.labels(method='post', endpoint='/submit').inc()
流程收集器

Python客户端自动导出有关进程CPU使用率,RAM,
文件描述符和开始时间的指标。这些都有前缀process,
目前只在Linux上可用。

命名空间和pid构造函数参数允许导出有关
其他进程的度量标准,例如:

ProcessCollector(namespace='mydaemon', pid=lambda: open('/var/run/daemon.pid').read())
出口

导出指标有多种选择。

HTTP

度量标准通常通过HTTP公开,由Prometheus服务器读取。

最简单的方法是via start_http_server,它将
在给定端口上的守护程序线程中启动HTTP 服务器:

from prometheus_client import start_http_server

start_http_server(8000)

访问http:// localhost:8000 /查看指标。

要将Prometheus展示添加到现有HTTP服务器,请参阅 提供a 的MetricsHandler类。它还可以作为如何 编写自定义端点的简单示例。
BaseHTTPRequestHandler

Twisted

To use prometheus with twisted, there is MetricsResource which exposes metrics as a twisted resource.

from prometheus_client.twisted import MetricsResource
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor

root = Resource()
root.putChild(b'metrics', MetricsResource())

factory = Site(root)
reactor.listenTCP(8000, factory)
reactor.run()
WSGI

要将Prometheus与WSGI一起使用,make_wsgi_app可以创建一个WSGI应用程序。

from prometheus_client import make_wsgi_app
from wsgiref.simple_server import make_server

app = make_wsgi_app()
httpd = make_server('', 8000, app)
httpd.serve_forever()

将Prometheus指标与WSGI
应用程序集成时,此类应用程序非常有用。

该方法start_wsgi_server可用于通过新线程中的WSGI引用实现来提供度量。

from prometheus_client import start_wsgi_server

start_wsgi_server(8000)
节点导出器文本文件收集器

的文本文件集电极允许机级统计经由节点出口被导出的。

这对于监视cronjobs或编写cronjobs以暴露
有关机器系统的指标非常有用,这些指标是节点导出器不支持或
在每次刮擦时都没有意义(例如,涉及子进程的任何事情)。

from prometheus_client import CollectorRegistry, Gauge, write_to_textfile

registry = CollectorRegistry()
g = Gauge('raid_status', '1 if raid array is okay', registry=registry)
g.set(1)
write_to_textfile('/configured/textfile/path/raid.prom', registry)

使用单独的注册表,因为默认注册表可能包含其他指标,
例如来自Process Collector的指标。

导出到Pushgateway

该Pushgateway
允许短暂和批处理作业到他们的指标暴露于普罗米修斯。

from prometheus_client import CollectorRegistry, Gauge, push_to_gateway

registry = CollectorRegistry()
g = Gauge('job_last_success_unixtime', 'Last time a batch job successfully finished', registry=registry)
g.set_to_current_time()
push_to_gateway('localhost:9091', job='batchA', registry=registry)

使用单独的注册表,因为默认注册表可能包含其他指标,
例如来自Process Collector的指标。

Pushgateway功能采用分组键。push_to_gateway使用
相同的分组键pushadd_to_gateway替换度量标准,仅替换具有
相同名称和分组键的delete_from_gateway度量标准,并使用
给定的作业和分组键删除度量标准。有关 更多信息,请参阅
Pushgateway文档。

instance_ip_grouping_key返回分组键,实例标签设置
为主机的IP地址。

桥梁

也可以将指标公开给Prometheus以外的系统。
这使您可以利用Prometheus仪器,即使
您尚未准备好完全过渡到Prometheus。

石墨

度量标准以Graphite明文格式通过TCP推送。

from prometheus_client.bridge.graphite import GraphiteBridge

gb = GraphiteBridge(('graphite.your.org', 2003))
# Push once.
gb.push()
# Push every 10 seconds in a daemon thread.
gb.start(10.0)
Custom Collectors

有时候直接检测代码是不可能的,因为它不在
您的控制范围内。这要求您从其他系统代理指标。

为此,您需要创建自定义收集器,例如:

from prometheus_client.core import GaugeMetricFamily, CounterMetricFamily, REGISTRY

class CustomCollector(object):
    def collect(self):
        yield GaugeMetricFamily('my_gauge', 'Help text', value=7)
        c = CounterMetricFamily('my_counter_total', 'Help text', labels=['foo'])
        c.add_metric(['bar'], 1.7)
        c.add_metric(['baz'], 3.8)
        yield c

REGISTRY.register(CustomCollector())

SummaryMetricFamilyHistogramMetricFamily工作方式相似。

分析器

Python客户端支持解析Promeheus文本格式。
这适用于您有服务器
公开Prometheus指标并需要将它们放入其他
系统的高级用例。

from prometheus_client.parser import text_string_to_metric_families
for family in text_string_to_metric_families("my_gauge 1.0\n"):
  for sample in family.samples:
    print("Name: {0} Labels: {1} Value: {2}".format(*sample))
上一篇 下一篇

猜你喜欢

热点阅读